Wednesday, October 6, 2021

Real Python: Python's sum(): The Pythonic Way to Sum Values

Python’s built-in function sum() is an efficient and Pythonic way to sum a list of numeric values. Adding several numbers together is a common intermediate step in many computations, so sum() is a pretty handy tool for a Python programmer.

As an additional and interesting use case, you can concatenate lists and tuples using sum(), which can be convenient when you need to flatten a list of lists.

In this tutorial, you’ll learn how to:

  • Sum numeric values by hand using general techniques and tools
  • Use Python’s sum() to add several numeric values efficiently
  • Concatenate lists and tuples with sum()
  • Use sum() to approach common summation problems
  • Use appropriate values for the arguments in sum()
  • Decide between sum() and alternative tools to sum and concatenate objects

This knowledge will help you efficiently approach and solve summation problems in your code using either sum() or other alternative and specialized tools.

Free Bonus: Click here to get a Python Cheat Sheet and learn the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.

Understanding the Summation Problem

Summing numeric values together is a fairly common problem in programming. For example, say you have a list of numbers [1, 2, 3, 4, 5] and want to add them together to compute their total sum. With standard arithmetic, you’ll do something like this:

1 + 2 + 3 + 4 + 5 = 15

As far as math goes, this expression is pretty straightforward. It walks you through a short series of additions until you find the sum of all the numbers.

It’s possible to do this particular calculation by hand, but imagine some other situations where it might not be so possible. If you have a particularly long list of numbers, adding by hand can be inefficient and error-prone. What happens if you don’t even know how many items are in the list? Finally, imagine a scenario where the number of items you need to add changes dynamically or unpredictably.

In situations like these, whether you have a long or short list of numbers, Python can be quite useful to solve summation problems.

If you want to sum the numbers by creating your own solution from scratch, then you can try using a for loop:

>>>
>>> numbers = [1, 2, 3, 4, 5]
>>> total = 0

>>> for number in numbers:
...     total += number
...

>>> total
15

Here, you first create total and initialize it to 0. This variable works as an accumulator in which you store intermediate results until you get the final one. The loop iterates through numbers and updates total by accumulating each successive value using an augmented assignment.

You can also wrap the for loop in a function. This way, you can reuse the code for different lists:

>>>
>>> def sum_numbers(numbers):
...     total = 0
...     for number in numbers:
...         total += number
...     return total
...

>>> sum_numbers([1, 2, 3, 4, 5])
15

>>> sum_numbers([])
0

In sum_numbers(), you take an iterable—specifically, a list of numeric values—as an argument and return the total sum of the values in the input list. If the input list is empty, then the function returns 0. The for loop is the same one that you saw before.

You can also use recursion instead of iteration. Recursion is a functional programming technique where a function is called within its own definition. In other words, a recursive function calls itself in a loop:

>>>
>>> def sum_numbers(numbers):
...     if len(numbers) == 0:
...         return 0
...     return numbers[0] + sum_numbers(numbers[1:])
...

>>> sum_numbers([1, 2, 3, 4, 5])
15

When you define a recursive function, you take the risk of running into an infinite loop. To prevent this, you need to define both a base case that stops the recursion and a recursive case to call the function and start the implicit loop.

In the above example, the base case implies that the sum of a zero-length list is 0. The recursive case implies that the total sum is the first value, numbers[0], plus the sum of the rest of the values, numbers[1:]. Because the recursive case uses a shorter sequence on each iteration, you expect to run into the base case when numbers is a zero-length list. As a final result, you get the sum of all the items in your input list, numbers.

Note: In this example, if you don’t check for an empty input list (your base case), then sum_numbers() will never run into an infinite recursive loop. When your numbers list reaches a length of 0, the code tries to access an item from the empty list, which raises an IndexError and breaks the loop.

With this kind of implementation, you’ll never get a sum from this function. You’ll get an IndexError every time.

Another option to sum a list of numbers in Python is to use reduce() from functools. To get the sum of a list of numbers, you can pass either operator.add or an appropriate lambda function as the first argument to reduce():

>>>
>>> from functools import reduce
>>> from operator import add

>>> reduce(add, [1, 2, 3, 4, 5])
15

>>> reduce(add, [])
Traceback (most recent call last):
    ...
TypeError: reduce() of empty sequence with no initial value

>>> reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])
15

Read the full article at https://realpython.com/python-sum-function/ »


[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...