Miscellaneous Tips
Explore practical Python tips including using sum() efficiently, proper string concatenation methods, saving data with pickling, and utilizing input() history features to improve your code's performance and maintainability.
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 ...