Miscellaneous Tips
Learn how to use sum(), pickle, and input() functions.
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:
Press + to interact
data = {1, 1, 1, 1, 2, 3} # set() eliminates duplicatesmean = sum(data) / len(data)print(mean)
In fact, sum()
is an optimized accumulator loop like this:
Press + to interact
def sum(iterable, init=0):for x in iterable:init += xreturn initprint(sum([2,4,6,8]))
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 ...