Using Alternatives to sum()
Using Alternatives to
sum(). As you’ve already learned,
sum() is helpful for working with numeric values in general. However, when it comes to working with floating-point numbers, Python provides an alternative tool.
If your code is constantly summing floating-point numbers with
sum(), then you should consider using
math.fsum() instead. This function performs floating-point computations more carefully than
sum(), which improves the precision of your computation. According to its documentation,
fsum() avoids loss of precision by tracking multiple intermediate partial sums.
If you want to work with a list instead, then you can use
list() to consume the iterator and return a regular Python list.
chain() is also a good option for flattening a list of lists in Python.
To flatten a list of lists with
chain(), you need to use the iterable unpacking operator (
*). This operator unpacks all the input variables so that
chain() can work with them and generate the corresponding iterator.
If you need to do so, then the preferred and fastest tool available in Python is the
str.join() method. This method takes a sequence of strings as an argument and returns a new, concatenated string.
.join() 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
.join() uses the string on which you call the method as a separator during the concatenation. In this example, you call
.join() on a string that consists of a single space (
" ") so that the original strings from
greeting are separated by spaces in the final string.
Become a Member to join the conversation.