Reputation:
total = sum([float(item) for item in s.split(",")])
total = sum(float(item) for item in s.split(","))
Source: https://stackoverflow.com/a/21212727/1825083
Upvotes: 4
Views: 150
Reputation: 34493
The first one makes a list while the second one is a generator expression. Try them without the sum()
function call.
In [25]: [float(a) for a in s.split(',')]
Out[25]: [1.23, 2.4, 3.123]
In [26]: (float(a) for a in s.split(','))
Out[26]: <generator object <genexpr> at 0x0698EF08>
In [27]: m = (float(a) for a in s.split(','))
In [28]: next(m)
Out[28]: 1.23
In [29]: next(m)
Out[29]: 2.4
In [30]: next(m)
Out[30]: 3.123
So, the first expression creates the whole list in memory first and then computes the sum whereas the second one just gets the next item in the expression and adds it to its current total. (More memory efficient)
Upvotes: 4
Reputation: 365717
The first one uses a list comprehension to build a list of all of the float values.
The second one uses a generator expression to build a generator that only builds each float value as requested, one a time. This saves a lot of memory when the list would be very large.
The generator expression may also be either faster (because it allows work to be pipelined, and avoids memory allocation times) or slower (because it adds a bit of overhead), but that's usually not a good reason to choose between them. Just follow this simple rule of thumb:
If you need a list (or, more likely, just something you can store, loop over multiple times, print out, etc.), build a list. If you just need to loop over the values, don't build a list.
In this case, obviously, you don't need a list, so leave the square brackets off.
In Python 2.x, there are some other minor differences; in 3.x, a list comprehension is actually defined as just calling the list
function on a generator expression. (Although there is a minor bug in at least 3.0-3.3 which you will only find if you go looking for it very hard…)
Upvotes: 5
Reputation: 2028
As others have said, the first creates a list, while the second creates a generator that generates all the values. The reason you might care about this is that creating the list puts all the elements into memory at once, whereas with the generator, you can process them as they are generated without having to store them all, which might matter for very large amounts of data.
Upvotes: 1
Reputation: 113955
The first one creates a list, and the sums the numbers in the list. It is a list comprehension inside a sum
The second one computes each item in turn and adds it to a running total, and returns that running total as the sum, when all items are exhausted. This is a generator comprehension.
It does not create a list at all, which means that it doesn't take extra time to allocate memory for a list and populate it. This also means that it has a better space complexity, as it only uses constant space (for the call to float
; aside from the call to split
, which both line do)
Upvotes: 0