Getting Started With Python's sum()
00:12 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.
You call some with the following two arguments.
iterable is a required argument that can hold any Python iterable. The iterable typically contains numeric values, but can also contain lists, or tuples.
start is an optional argument that can hold an initial value. This value is then added to the final result, and it defaults to
start plus the values in the iterable from left to right. The optional argument
start can accept a number, list, or tuple, depending on what’s passed to the iterable. It can’t take a string.
Accepting any Python iterable as its first argument makes
sum() generic, reusable, and polymorphic. Because of this feature, you can use
sum() with lists, tuples, sets,
range objects, and dictionaries, summing the keys both implicitly and explicitly.
The second, optional argument,
start, allows you to provide a value to initialize the summation process. This argument is handy when you need to process cumulative values sequentially and can be provided as a positional argument or a keyword argument.
If you don’t provide a value to
start, it defaults to zero. This default value ensures the expected behavior of returning the total sum of the input values. In the next section of the course, you’ll work further with
sum(), looking at summation of numeric values and concatenation of sequences.
Become a Member to join the conversation.