10. Use list comprehensions

The key here is to avoid looping over elements and storing results. Instead, use a for or generator comprehension. Note that the for (note the brackets) comprehension eagerly evaluates the expressions and returns a list, but the generator (note the parentheses) lazily evaluates the expressions.

10.1. Don’t do this

1results = []
2
3for i in range(10):
4    s = i ** 2
5    results.append(s)
6
7total = sum(results)

10.2. Do this

1total = sum([i ** 2 for i in range(10)])
1total = sum((i ** 2 for i in range(10)))