Summing Numeric Values and Concatenating Sequences
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
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.
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.
Become a Member to join the conversation.