Miscellaneous Tips
Learn how to use sum(), pickle, and input() functions.
We'll cover the following...
We'll cover the following...
sum() almost anything
The built-in sum() function is an excellent tool for summing up all numbers in an iterable and for operations dependent on such summation. For example, we can easily calculate the mean of a set, even if we don’t have access to statistics, numpy, scipy, or a similar module:
In fact, sum() is an optimized accumulator loop like this:
A notable exception
There is one notable exception. That is, sum() doesn’t allow us to concatenate a collection of strings. Concatenating a large list of strings is prohibitively inefficient. It is inefficient to the extent that Python developers invoked two rarely combined principles from The Zen of Python:
- Special cases aren’t special enough to break the rules (so, let
sum()concatenate strings). - Practicality beats purity.
We should avoid a list and tuple summation with ...