Can we use sum function in tuple in Python?

Python’s built-in function >>> 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 9 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 >>> 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 9 is a pretty handy tool for a Python programmer.

As an additional and interesting use case, you can concatenate lists and tuples using >>> 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 9, 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 >>> 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 9 to add several numeric values efficiently
  • Concatenate lists and tuples with >>> 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 9
  • Use >>> 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 9 to approach common summation problems
  • Use appropriate values for the arguments in >>> 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 9
  • Decide between >>> 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 9 and alternative tools to sum and concatenate objects

This knowledge will help you efficiently approach and solve summation problems in your code using either >>> 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 9 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 >>> 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 8 loop:

>>>>>> numbers = [1, 2, 3, 4, 5] >>> total = 0 >>> for number in numbers: ... total += number ... >>> total 15

Here, you first create >>> 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 9 and initialize it to >>> sum([1, 2, 3, 4, 5]) 15 >>> sum([]) 0 0. This variable works as an accumulator in which you store intermediate results until you get the final one. The loop iterates through >>> sum([1, 2, 3, 4, 5]) 15 >>> sum([]) 0 1 and updates >>> 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 9 by accumulating each successive value using an .

You can also wrap the >>> 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 8 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([1, 2, 3, 4, 5]) 15 >>> sum([]) 0 4, you take an —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 >>> sum([1, 2, 3, 4, 5]) 15 >>> sum([]) 0 0. The >>> 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 8 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 >>> sum([1, 2, 3, 4, 5]) 15 >>> sum([]) 0 0. The recursive case implies that the total sum is the first value, >>> sum([1, 2, 3, 4, 5]) 15 >>> sum([]) 0 8, plus the sum of the rest of the values, >>> sum([1, 2, 3, 4, 5]) 15 >>> sum([]) 0 9. Because the recursive case uses a shorter sequence on each iteration, you expect to run into the base case when >>> sum([1, 2, 3, 4, 5]) 15 >>> sum([]) 0 1 is a zero-length list. As a final result, you get the sum of all the items in your input list, >>> sum([1, 2, 3, 4, 5]) 15 >>> sum([]) 0 1.

Note: In this example, if you don’t check for an empty input list (your base case), then >>> sum([1, 2, 3, 4, 5]) 15 >>> sum([]) 0 4 will never run into an infinite recursive loop. When your >>> sum([1, 2, 3, 4, 5]) 15 >>> sum([]) 0 1 list reaches a length of >>> sum([1, 2, 3, 4, 5]) 15 >>> sum([]) 0 0, the code tries to access an item from the empty list, which raises an >>> # Use a list >>> sum([1, 2, 3, 4, 5]) 15 >>> # Use a tuple >>> sum((1, 2, 3, 4, 5)) 15 >>> # Use a set >>> sum({1, 2, 3, 4, 5}) 15 >>> # Use a range >>> sum(range(1, 6)) 15 >>> # Use a dictionary >>> sum({1: "one", 2: "two", 3: "three"}) 6 >>> sum({1: "one", 2: "two", 3: "three"}.keys()) 6 5 and breaks the loop.

With this kind of implementation, you’ll never get a sum from this function. You’ll get an >>> # Use a list >>> sum([1, 2, 3, 4, 5]) 15 >>> # Use a tuple >>> sum((1, 2, 3, 4, 5)) 15 >>> # Use a set >>> sum({1, 2, 3, 4, 5}) 15 >>> # Use a range >>> sum(range(1, 6)) 15 >>> # Use a dictionary >>> sum({1: "one", 2: "two", 3: "three"}) 6 >>> sum({1: "one", 2: "two", 3: "three"}.keys()) 6 5 every time.

Another option to sum a list of numbers in Python is to use >>> # Use a list >>> sum([1, 2, 3, 4, 5]) 15 >>> # Use a tuple >>> sum((1, 2, 3, 4, 5)) 15 >>> # Use a set >>> sum({1, 2, 3, 4, 5}) 15 >>> # Use a range >>> sum(range(1, 6)) 15 >>> # Use a dictionary >>> sum({1: "one", 2: "two", 3: "three"}) 6 >>> sum({1: "one", 2: "two", 3: "three"}.keys()) 6 7 from . To get the sum of a list of numbers, you can pass either or an appropriate >>> sum([x ** 2 for x in range(1, 6)]) 55 0 function as the first argument to >>> # Use a list >>> sum([1, 2, 3, 4, 5]) 15 >>> # Use a tuple >>> sum((1, 2, 3, 4, 5)) 15 >>> # Use a set >>> sum({1, 2, 3, 4, 5}) 15 >>> # Use a range >>> sum(range(1, 6)) 15 >>> # Use a dictionary >>> sum({1: "one", 2: "two", 3: "three"}) 6 >>> sum({1: "one", 2: "two", 3: "three"}.keys()) 6 7:

>>>>>> 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

You can call >>> # Use a list >>> sum([1, 2, 3, 4, 5]) 15 >>> # Use a tuple >>> sum((1, 2, 3, 4, 5)) 15 >>> # Use a set >>> sum({1, 2, 3, 4, 5}) 15 >>> # Use a range >>> sum(range(1, 6)) 15 >>> # Use a dictionary >>> sum({1: "one", 2: "two", 3: "three"}) 6 >>> sum({1: "one", 2: "two", 3: "three"}.keys()) 6 7 with a reduction, or folding, >>> sum([x ** 2 for x in range(1, 6)]) 55 3 along with an >>> sum([x ** 2 for x in range(1, 6)]) 55 4 as arguments. Then >>> # Use a list >>> sum([1, 2, 3, 4, 5]) 15 >>> # Use a tuple >>> sum((1, 2, 3, 4, 5)) 15 >>> # Use a set >>> sum({1, 2, 3, 4, 5}) 15 >>> # Use a range >>> sum(range(1, 6)) 15 >>> # Use a dictionary >>> sum({1: "one", 2: "two", 3: "three"}) 6 >>> sum({1: "one", 2: "two", 3: "three"}.keys()) 6 7 uses the input function to process >>> sum([x ** 2 for x in range(1, 6)]) 55 4 and returns a single cumulative value.

In the first example, the reduction function is >>> sum([x ** 2 for x in range(1, 6)]) 55 7, which takes two numbers and adds them together. The final result is the sum of the numbers in the input >>> sum([x ** 2 for x in range(1, 6)]) 55 4. As a drawback, >>> # Use a list >>> sum([1, 2, 3, 4, 5]) 15 >>> # Use a tuple >>> sum((1, 2, 3, 4, 5)) 15 >>> # Use a set >>> sum({1, 2, 3, 4, 5}) 15 >>> # Use a range >>> sum(range(1, 6)) 15 >>> # Use a dictionary >>> sum({1: "one", 2: "two", 3: "three"}) 6 >>> sum({1: "one", 2: "two", 3: "three"}.keys()) 6 7 raises a when you call it with an empty >>> sum([x ** 2 for x in range(1, 6)]) 55 4.

In the second example, the reduction function is a >>> sum([x ** 2 for x in range(1, 6)]) 55 0 function that returns the addition of two numbers.

Since summations like these are commonplace in programming, coding a new function every time you need to sum some numbers is a lot of repetitive work. Additionally, using >>> # Use a list >>> sum([1, 2, 3, 4, 5]) 15 >>> # Use a tuple >>> sum((1, 2, 3, 4, 5)) 15 >>> # Use a set >>> sum({1, 2, 3, 4, 5}) 15 >>> # Use a range >>> sum(range(1, 6)) 15 >>> # Use a dictionary >>> sum({1: "one", 2: "two", 3: "three"}) 6 >>> sum({1: "one", 2: "two", 3: "three"}.keys()) 6 7 isn’t the most readable solution available to you.

Python provides a dedicated built-in function to solve this problem. The function is conveniently called . Since it’s a built-in function, you can use it directly in your code without importing anything.

Remove ads

Getting Started With Python’s >>> 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 9

Readability is one of the most important principles behind . Visualize what you are asking a loop to do when summing a list of values. You want it to loop over some numbers, accumulate them in an intermediate variable, and return the final sum. However, you can probably imagine a more readable version of summation that doesn’t need a loop. You want Python to take some numbers and sum them together.

Now think about how >>> # Use a list >>> sum([1, 2, 3, 4, 5]) 15 >>> # Use a tuple >>> sum((1, 2, 3, 4, 5)) 15 >>> # Use a set >>> sum({1, 2, 3, 4, 5}) 15 >>> # Use a range >>> sum(range(1, 6)) 15 >>> # Use a dictionary >>> sum({1: "one", 2: "two", 3: "three"}) 6 >>> sum({1: "one", 2: "two", 3: "three"}.keys()) 6 7 does summation. Using >>> # Use a list >>> sum([1, 2, 3, 4, 5]) 15 >>> # Use a tuple >>> sum((1, 2, 3, 4, 5)) 15 >>> # Use a set >>> sum({1, 2, 3, 4, 5}) 15 >>> # Use a range >>> sum(range(1, 6)) 15 >>> # Use a dictionary >>> sum({1: "one", 2: "two", 3: "three"}) 6 >>> sum({1: "one", 2: "two", 3: "three"}.keys()) 6 7 is arguably less readable and less straightforward than even the loop-based solution.

This is why Python 2.3 added >>> 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 9 as a built-in function to provide a Pythonic solution to the summation problem. Alex Martelli contributed the function, which nowadays is the preferred syntax for summing a list of values:

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

Wow! That’s neat, isn’t it? It reads like plain English and clearly communicates the action you’re performing on the input list. Using >>> 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 9 is way more readable than a >>> 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 8 loop or a >>> # Use a list >>> sum([1, 2, 3, 4, 5]) 15 >>> # Use a tuple >>> sum((1, 2, 3, 4, 5)) 15 >>> # Use a set >>> sum({1, 2, 3, 4, 5}) 15 >>> # Use a range >>> sum(range(1, 6)) 15 >>> # Use a dictionary >>> sum({1: "one", 2: "two", 3: "three"}) 6 >>> sum({1: "one", 2: "two", 3: "three"}.keys()) 6 7 call. Unlike >>> # Use a list >>> sum([1, 2, 3, 4, 5]) 15 >>> # Use a tuple >>> sum((1, 2, 3, 4, 5)) 15 >>> # Use a set >>> sum({1, 2, 3, 4, 5}) 15 >>> # Use a range >>> sum(range(1, 6)) 15 >>> # Use a dictionary >>> sum({1: "one", 2: "two", 3: "three"}) 6 >>> sum({1: "one", 2: "two", 3: "three"}.keys()) 6 7, >>> 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 9 doesn’t raise a >>> sum(x ** 2 for x in range(1, 6)) 55 0 when you provide an empty iterable. Instead, it understandably returns >>> sum([1, 2, 3, 4, 5]) 15 >>> sum([]) 0 0.

You can call >>> 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 9 with the following two arguments:

  1. >>> sum([x ** 2 for x in range(1, 6)]) 55 4 is a required argument that can hold any Python iterable. The iterable typically contains numeric values but can also contain lists or tuples.
  2. >>> sum([1, 2, 3, 4, 5], 100) # Positional argument 115 >>> sum([1, 2, 3, 4, 5], start=100) # Keyword argument 115 8 is an optional argument that can hold an initial value. This value is then added to the final result. It defaults to >>> sum([1, 2, 3, 4, 5]) 15 >>> sum([]) 0 0.

Internally, >>> 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 9 adds >>> sum([1, 2, 3, 4, 5], 100) # Positional argument 115 >>> sum([1, 2, 3, 4, 5], start=100) # Keyword argument 115 8 plus the values in >>> sum([x ** 2 for x in range(1, 6)]) 55 4 from left to right. The values in the input >>> sum([x ** 2 for x in range(1, 6)]) 55 4 are normally numbers, but you can also use lists and tuples. The optional argument >>> sum([1, 2, 3, 4, 5], 100) # Positional argument 115 >>> sum([1, 2, 3, 4, 5], start=100) # Keyword argument 115 8 can accept a number, list, or tuple, depending on what is passed to >>> sum([x ** 2 for x in range(1, 6)]) 55 4. It can’t take a string.

In the following two sections, you’ll learn the basics of using >>> 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 9 in your code.

The Required Argument: >>> sum([x ** 2 for x in range(1, 6)]) 55 4

Accepting any Python iterable as its first argument makes >>> 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 9 generic, reusable, and polymorphic. Because of this feature, you can use >>> 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 9 with lists, tuples, sets, >>> 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 00 objects, and dictionaries:

>>>>>> # Use a list >>> sum([1, 2, 3, 4, 5]) 15 >>> # Use a tuple >>> sum((1, 2, 3, 4, 5)) 15 >>> # Use a set >>> sum({1, 2, 3, 4, 5}) 15 >>> # Use a range >>> sum(range(1, 6)) 15 >>> # Use a dictionary >>> sum({1: "one", 2: "two", 3: "three"}) 6 >>> sum({1: "one", 2: "two", 3: "three"}.keys()) 6

In all these examples, >>> 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 9 computes the arithmetic sum of all the values in the input iterable regardless of their types. In the two dictionary examples, both calls to >>> 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 9 return the sum of the keys of the input dictionary. The first example sums the keys by default and the second example sums the keys because of the call on the input dictionary.

If your dictionary stores numbers in its values and you would like to sum these values instead of the keys, then you can do this by using just like in the >>> 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 03 example.

You can also use >>> 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 9 with a list comprehension as an argument. Here’s an example that computes the sum of the squares of a range of values:

>>>>>> sum([x ** 2 for x in range(1, 6)]) 55

added to the language. Again, >>> 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 9 works as expected when you use a generator expression as an argument:

>>>>>> sum(x ** 2 for x in range(1, 6)) 55

This example shows one of the most Pythonic techniques to approach the summation problem. It provides an elegant, readable, and efficient solution in a single line of code.

Remove ads

The Optional Argument: >>> sum([1, 2, 3, 4, 5], 100) # Positional argument 115 >>> sum([1, 2, 3, 4, 5], start=100) # Keyword argument 115 8

The second and optional argument, >>> sum([1, 2, 3, 4, 5], 100) # Positional argument 115 >>> sum([1, 2, 3, 4, 5], start=100) # Keyword argument 115 8, allows you to provide a value to initialize the summation process. This argument is handy when you need to process cumulative values sequentially:

>>>>>> sum([1, 2, 3, 4, 5], 100) # Positional argument 115 >>> sum([1, 2, 3, 4, 5], start=100) # Keyword argument 115

Here, you provide an initial value of >>> 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 10 to >>> sum([1, 2, 3, 4, 5], 100) # Positional argument 115 >>> sum([1, 2, 3, 4, 5], start=100) # Keyword argument 115 8. The net effect is that >>> 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 9 adds this value to the cumulative sum of the values in the input iterable. Note that you can provide >>> sum([1, 2, 3, 4, 5], 100) # Positional argument 115 >>> sum([1, 2, 3, 4, 5], start=100) # Keyword argument 115 8 as a or as a . The latter option is way more explicit and readable.

If you don’t provide a value to >>> sum([1, 2, 3, 4, 5], 100) # Positional argument 115 >>> sum([1, 2, 3, 4, 5], start=100) # Keyword argument 115 8, then it defaults to >>> sum([1, 2, 3, 4, 5]) 15 >>> sum([]) 0 0. A default value of >>> sum([1, 2, 3, 4, 5]) 15 >>> sum([]) 0 0 ensures the expected behavior of returning the total sum of the input values.

Summing Numeric Values

The primary purpose of >>> 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 9 is to provide a Pythonic way to add numeric values together. Up to this point, you’ve seen how to use the function to sum integer numbers. Additionally, you can use >>> 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 9 with any other numeric Python types, such as , >>> 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 20, , and .

Here are a few examples of using >>> 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 9 with values of different numeric types:

>>>>>> from decimal import Decimal >>> from fractions import Fraction >>> # Sum floating-point numbers >>> sum([10.2, 12.5, 11.8]) 34.5 >>> sum([10.2, 12.5, 11.8, float("inf")]) inf >>> sum([10.2, 12.5, 11.8, float("nan")]) nan >>> # Sum complex numbers >>> sum([3 + 2j, 5 + 6j]) (8+8j) >>> # Sum Decimal numbers >>> sum([Decimal("10.2"), Decimal("12.5"), Decimal("11.8")]) Decimal('34.5') >>> # Sum Fraction numbers >>> sum([Fraction(51, 5), Fraction(25, 2), Fraction(59, 5)]) Fraction(69, 2)

Here, you first use >>> 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 9 with floating-point numbers. It’s worth noting the function’s behavior when you use the special symbols >>> 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 25 and >>> 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 26 in the calls >>> 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 27 and >>> 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 28. The first symbol represents an infinite value, so >>> 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 9 returns >>> 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 25. The second symbol represents NaN (not a number) values. Since you can’t add numbers with non-numbers, you get >>> 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 26 as a result.

The other examples sum iterables of >>> 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 20, >>> 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 33, and >>> 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 34 numbers. In all cases, >>> 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 9 returns the resulting cumulative sum using the appropriate numeric type.

Concatenating Sequences

Even though >>> 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 9 is mostly intended to operate on numeric values, you can also use the function to concatenate sequences such as lists and tuples. To do that, you need to provide an appropriate value to >>> sum([1, 2, 3, 4, 5], 100) # Positional argument 115 >>> sum([1, 2, 3, 4, 5], start=100) # Keyword argument 115 8:

>>>>>> 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 0

In these examples, you use >>> 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 9 to concatenate lists and tuples. This is an interesting feature that you can use to flatten a list of lists or a tuple of tuples. The key requirement for these examples to work is to select an appropriate value for >>> sum([1, 2, 3, 4, 5], 100) # Positional argument 115 >>> sum([1, 2, 3, 4, 5], start=100) # Keyword argument 115 8. For example, if you want to concatenate lists, then >>> sum([1, 2, 3, 4, 5], 100) # Positional argument 115 >>> sum([1, 2, 3, 4, 5], start=100) # Keyword argument 115 8 needs to hold a list.

In the examples above, >>> 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 9 is internally performing a concatenation operation, so it works only with those sequence types that support concatenation, with the exception of strings:

>>>>>> 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 1

When you try to use >>> 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 9 to concatenate strings, you get a >>> sum(x ** 2 for x in range(1, 6)) 55 0. As the exception message suggests, you should use to concatenate strings in Python. You’ll see examples of using this method later on when you get to the section on .

Practicing With Python’s >>> 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 9

So far, you’ve learned the basics of working with >>> 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 9. You’ve learned how to use this function to add numeric values together and also to concatenate sequences such as lists and tuples.

In this section, you’ll look at some more examples of when and how to use >>> 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 9 in your code. With these practical examples, you’ll learn that this built-in function is quite handy when you’re performing computations that require finding the sum of a series of numbers as an intermediate step.

You’ll also learn that >>> 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 9 can be helpful when you’re working with lists and tuples. A special example you’ll look at is when you need to flatten a list of lists.

Remove ads

Computing Cumulative Sums

The first example you’ll code has to do with how to take advantage of the >>> sum([1, 2, 3, 4, 5], 100) # Positional argument 115 >>> sum([1, 2, 3, 4, 5], start=100) # Keyword argument 115 8 argument for summing cumulative lists of numeric values.

Say you’re developing a system to manage the sales of a given product at several different points of sale. Every day, you get a sold units report from each point of sale. You need to systematically compute the cumulative sum to know how many units the whole company sold over the week. To solve this problem, you can use >>> 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 9:

>>>>>> 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 2

By using >>> sum([1, 2, 3, 4, 5], 100) # Positional argument 115 >>> sum([1, 2, 3, 4, 5], start=100) # Keyword argument 115 8, you set an initial value to initialize the sum, which allows you to add successive units to the previously computed subtotal. At the end of the week, you’ll have the company’s total count of sold units.

Calculating the Mean of a Sample

Another practical use case of >>> 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 9 is to use it as an intermediate calculation before doing further calculations. For example, say you need to calculate the arithmetic mean of a sample of numeric values. The arithmetic mean, also known as the average, is the total sum of the values divided by the number of values, or , in the sample.

If you have the sample [2, 3, 4, 2, 3, 6, 4, 2] and you want to calculate the arithmetic mean by hand, then you can solve this operation:

(2 + 3 + 4 + 2 + 3 + 6 + 4 + 2) / 8 = 3.25

If you want to speed this up by using Python, you can break it up into two parts. The first part of this computation, where you are adding together the numbers, is a task for >>> 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 9. The next part of the operation, where you are dividing by 8, uses the count of numbers in your sample. To calculate your divisor, you can use >>> 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 55:

>>>>>> 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 3

Here, the call to >>> 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 9 computes the total sum of the data points in your sample. Next, you use >>> 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 55 to get the number of data points. Finally, you perform the required division to calculate the sample’s arithmetic mean.

In practice, you may want to turn this code into a function with some additional features, such as a descriptive name and a check for empty samples:

>>>>>> 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 4

Inside >>> 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 58, you first check if the input sample has any data points. If not, then you raise a >>> 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 59 with a descriptive message. In this example, you use the to store the number of data points in the variable >>> 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 60 so that you won’t need to call >>> 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 55 again. The return statement computes the sample’s arithmetic mean and sends it back to the calling code.

Note: Computing the mean of a sample of data is a common operation in statistics and data analysis. The Python standard library provides a convenient module called to approach these kinds of calculations.

In the >>> 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 62 module, you’ll find a function called :

>>>>>> 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 5

The >>> 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 65 function has very similar behavior to the >>> 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 58 function you coded earlier. When you call >>> 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 64 with a sample of numeric values, you’ll get the arithmetic mean of the input data. When you pass an empty list to >>> 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 64, you’ll get a >>> 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 69.

Note that when you call >>> 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 58 with a proper sample, you’ll get the desired mean. If you call >>> 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 58 with an empty sample, then you get a >>> 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 59 as expected.

Finding the Dot Product of Two Sequences

Another problem you can solve using >>> 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 9 is finding the dot product of two equal-length sequences of numeric values. The dot product is the algebraic sum of products of every pair of values in the input sequences. For example, if you have the sequences (1, 2, 3) and (4, 5, 6), then you can calculate their dot product by hand using addition and multiplication:

1 × 4 + 2 × 5 + 3 × 6 = 32

To extract successive pairs of values from the input sequences, you can use >>> 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 74. Then you can use a generator expression to multiply each pair of values. Finally, >>> 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 9 can sum the products:

>>>>>> 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 6

With >>> 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 74, you generate a list of tuples with the values from each of the input sequences. The generator expression loops over each tuple while multiplying the successive pairs of values previously arranged by >>> 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 74. The final step is to add the products together using >>> 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 9.

The code in the above example works. However, the dot product is defined for sequences of equal length, so what happens if you provide sequences with different lengths? In that case, >>> 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 74 ignores the extra values from the longest sequence, which leads to an incorrect result.

To deal with this possibility, you can wrap the call to >>> 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 9 in a custom function and provide a proper check for the length of the input sequences:

>>>>>> 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 7

Here, >>> 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 81 takes two sequences as arguments and returns their corresponding dot product. If the input sequences have different lengths, then the function raises a >>> 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 59.

Embedding the functionality in a custom function allows you to reuse the code. It also gives you the opportunity to name the function descriptively so that the user knows what the function does just by reading its name.

Remove ads

Flattening a List of Lists

Flattening a list of lists is a common task in Python. Say you have a list of lists and need to flatten it into a single list containing all the items from the original nested lists. You can use any of several approaches to flattening lists in Python. For example, you can use a >>> 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 8 loop, as in the following code:

>>>>>> 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 8

Inside >>> 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 84, the loop iterates over all the nested lists contained in >>> 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 85. Then it concatenates them in >>> 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 86 using an augmented assignment operation (>>> 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 87). As the result, you get a flat list with all the items from the original nested lists.

But hold on! You’ve already learned how to use >>> 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 9 to concatenate sequences in this tutorial. Can you use that feature to flatten a list of lists like you did in the example above? Yes! Here’s how:

>>>>>> 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 9

That was quick! A single line of code and >>> 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 89 is now a flat list. However, using >>> 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 9 doesn’t seem to be the fastest solution.

An important drawback of any solution that implies concatenation is that behind the scenes, every intermediate step creates a new list. This can be pretty wasteful in terms of memory usage. The list that is eventually returned is just the most recently created list out of all the lists that were created at each round of concatenation. Using a list comprehension instead ensures that you create and return only one list:

>>>>>> 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 0

This new version of >>> 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 84 is more efficient and less wasteful in terms of memory usage. However, the can be challenging to read and understand.

Using >>> 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 92 is probably the most readable and Pythonic way to flatten a list of lists:

>>>>>> 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 1

In this version of >>> 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 84, someone reading your code can see that the function iterates over every >>> 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 94 in >>> 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 85. Inside this first >>> 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 8 loop, it iterates over each >>> 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 97 in >>> 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 94 to finally populate the new >>> 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 86 list with >>> 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 92. Just like the comprehension from earlier, this solution creates only one list in the process. An advantage of this solution is that it is very readable.

Using Alternatives to >>> 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 9

As you’ve already learned, >>> 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 9 is helpful for working with numeric values in general. However, when it comes to working with floating-point numbers, Python provides an alternative tool. In >>> 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 03, you’ll find a function called that can help you improve the general precision of your floating-point computations.

You might have a task where you want to concatenate or chain several iterables so that you can work with them as one. For this scenario, you can look to the >>> 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 05 module’s function .

You might also have a task where you want to concatenate a list of strings. You’ve learned in this tutorial that there’s no way to use >>> 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 9 for concatenating strings. This function just wasn’t built for string concatenation. The most Pythonic alternative is to use .

Summing Floating-Point Numbers: >>> 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 09

If your code is constantly summing floating-point numbers with >>> 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 9, then you should consider using >>> 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 09 instead. This function performs floating-point computations more carefully than >>> 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 9, which improves the precision of your computation.

According to its , >>> 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 04 “avoids loss of precision by tracking multiple intermediate partial sums.” The documentation provides the following example:

>>>>>> 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 2

With >>> 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 04, you get a more precise result. However, you should note that >>> 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 04 doesn’t solve the error in floating-point arithmetic. The following example uncovers this limitation:

>>>>>> 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 3

In these examples, both functions return the same result. This is due to the impossibility of accurately representing both values >>> 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 16 and >>> 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 17 in binary floating-point:

>>>>>> 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 4

Unlike >>> 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 9, however, >>> 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 04 can help you reduce floating-point error propagation when you add very large and very small numbers together:

>>>>>> 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 5

Wow! The second example is pretty surprising and totally defeats >>> 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 9. With >>> 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 9, you get >>> 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 22 as a result. This is quite far away from the correct result of >>> 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 23, as you get with >>> 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 04.

Remove ads

Concatenating Iterables With >>> 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 25

If you’re looking for a handy tool for concatenating or chaining a series of iterables, then consider using >>> 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 06 from >>> 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 05. This function can take multiple iterables and build an that yields items from the first one, from the second one, and so on until it exhausts all the input iterables:

>>>>>> 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 6

When you call >>> 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 06, you get an iterator of the items from the input iterables. In this example, you access successive items from >>> sum([1, 2, 3, 4, 5]) 15 >>> sum([]) 0 1 using . If you want to work with a list instead, then you can use >>> 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 31 to consume the iterator and return a regular Python list.

>>> 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 06 is also a good option for flattening a list of lists in Python:

>>>>>> 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 7

To flatten a list of lists with >>> 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 06, you need to use the iterable unpacking operator (>>> 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 34). This operator unpacks all the input iterables so that >>> 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 06 can work with them and generate the corresponding iterator. The final step is to call >>> 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 31 to build the desired flat list.

Concatenating Strings With >>> 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 44

As you’ve already seen, >>> 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 9 doesn’t concatenate or join strings. If you need to do so, then the preferred and fastest tool available in Python is >>> 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 44. This method takes a sequence of strings as an argument and returns a new, concatenated string:

>>>>>> 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 8

Using >>> 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 40 is the most efficient and Pythonic way to concatenate strings. Here, you use a list of strings as an argument and build a single string from the input. Note that >>> 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 40 uses the string on which you call the method as a separator during the concatenation. In this example, you call >>> 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 40 on a string that consists of a single space character (>>> 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 43), so the original strings from >>> 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 44 are separated by spaces in your final string.

Conclusion

You can now use Python’s built-in function to add multiple numeric values together. This function provides an efficient, readable, and Pythonic way to solve summation problems in your code. If you’re dealing with math computations that require summing numeric values, then >>> 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 9 can be your lifesaver.

In this tutorial, you learned how to:

  • Sum numeric values using general techniques and tools
  • Add several numeric values efficiently using Python’s >>> 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 9
  • Concatenate sequences using >>> 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 9
  • Use >>> 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 9 to approach common summation problems
  • Use appropriate values for the >>> sum([x ** 2 for x in range(1, 6)]) 55 4 and >>> sum([1, 2, 3, 4, 5], 100) # Positional argument 115 >>> sum([1, 2, 3, 4, 5], start=100) # Keyword argument 115 8 arguments in >>> 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 9
  • Decide between >>> 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 9 and alternative tools to sum and concatenate objects

With this knowledge, you’re now able to add multiple numeric values together in a Pythonic, readable, and efficient way.

Mark as Completed

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Send Me Python Tricks »

About Leodanis Pozo Ramos

Leodanis is an industrial engineer who loves Python and software development. He's a self-taught Python developer with 6+ years of experience. He's an avid technical writer with a growing number of articles published on Real Python and other sites.

» More about Leodanis

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Aldren

Bartosz

Joanna

Jacob

Sadie

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

Master Real-World Python Skills
With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

What Do You Think?

Rate this article:

Tweet Share Share Email

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. and get answers to common questions in our support portal.

How do you use the sum function in a tuple in Python?

Method #1 : Using list() + sum() The above functions can be combined to perform this task. We can employ sum() to accumulate the result of summation logic.

Can we use sum function on tuple?

When it is required to sum the elements present in a list of tuple, the 'map' method and the 'sum' method can be used. A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).

How do you sum a tuple in a list Python?

Method #1 : Using sum() + map() A combination of the above functions can be used to solve this particular problem. In this the task of summation is performed by sum(), and applying the summation functionality to each element in tuple list is performed by map() method.

Can we add in tuple in Python?

Tuples are unchangeable, meaning that you cannot change, add, or remove items once the tuple is created.

Postingan terbaru

LIHAT SEMUA