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.

3 thoughts on “More efficient way to sum a list comprehension

  1. I haven’t been able to see a noticeable difference (calculating the sum of 1/k^2 for k = 1 to 1000). Is it advantageous for even larger lists, perhaps? I agree it’s more pleasing to read and write though.

Leave a Reply

Your email address will not be published. Required fields are marked *