Summing Numeric Values and Concatenating Sequences
00:00
Summing Numeric Values and Concatenation. The primary purpose of sum()
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 sum()
with any other numeric Python types, such as float
, complex
, decimal.Decimal
, and fractions.Fraction
.
00:28
On-screen are a few examples of using sum()
with values of different numeric types.
00:40
First, sum()
is used with floating-point numbers. It’s worth noting the function’s behavior when you use the special symbols inf
and nan
.
00:50
The first symbol represents an infinite value, so sum()
returns inf
. The second symbol, NaN
, represents Not a Number values.
00:59
Since you can’t add numbers with non-numbers, you get nan
as a result. You can also use sum()
with complex numbers, decimals,
01:25
In all cases, sum()
returns the resulting cumulative sum using the appropriate numeric type. Even though sum()
is mostly intended to operate on numeric values, you can also use the function to concatenate sequences such as lists and tuples.
01:44
To do that, you need to provide an appropriate value to start
.
01:52
If you supply an inappropriate value, you’ll get a TypeError
. You can perform the equivalent concatenation manually. Concatenating lists and tuples is an interesting feature that you can use to flatten a list of lists or a tuple of tuples. As you’ve already seen, the key requirement for these examples to work is to select an appropriate value for start
. To concatenate lists then, start
needs to hold a list.
02:25
sum()
is internally performing a concatenation operation, so it works with only those sequence types that support concatenation, with the exception of strings.
02:37
When you try to use sum()
to concatenate strings, you get a TypeError
. As the exception message suggests, you should use the str.join()
method to concatenate strings in Python.
02:50
You’ll see examples of using this method later on in the course when you’ll see some alternatives to using sum()
. But before that, in the next section, you’ll get more practice of using sum()
.
Become a Member to join the conversation.