More efficient way to sum a list comprehension

List comprehensions in Python let you create a list declaratively, much like the way you would describe the set in English.

For example, [x**2 for x in range(10)] creates a list of the squares of the numbers 0 through 9.

If you wanted the sum of these numbers, you could of course say sum( [x**2 for x in range(10)] ) but in this case the brackets are unnecessary.

The code is easier to read and more efficient if you omit the brackets.

sum( x**2 for x in range(10) ) With the brackets, Python constructs the list first then sums the elements.

Without the brackets, you have a generator expression.

Python will sum the values as they’re generated, not saving all the values in memory.

This makes no difference for a short list as above, but with a large list comprehension the generator expression could be more efficient.

.

Leave a Reply