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.
I was expecting to see a sum-of-squares formula appearing somewhere in this post :-)
That would be cheating. :)
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.
@Joss Noirel
Sure it it advantageous for very large lists, consider a case where you have to sum up a large number of items, given sufficiently big number of items to sum up, there wouldn’t be enough place in memory to store such a humongous list. Here come generator expressions to the rescue, such an expression produces a generator which is “lazy” and produces a stream of items one at a time, so we don’t run into such problems.