Search⌘ K
AI Features

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.

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:

Python 3.8
data = {1, 1, 1, 1, 2, 3} # set() eliminates duplicates
mean = sum(data) / len(data)
print(mean)

In fact, sum() is an optimized accumulator loop like this:

Python 3.8
def sum(iterable, init=0):
for x in iterable:
init += x
return init
print(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:

  1. Special cases aren’t special enough to break the rules (so, let sum() concatenate strings).
  2. Practicality beats purity.

We should avoid a list and tuple summation with ...