Reputation: 69
I'm trying to sum a list named mpg with the entry 'cty' (converted from a dictionary).
Sample data:
[{'': '1', 'trans': 'auto(l5)', 'drv': 'f', 'cty': '18'}, {'': '2', 'trans': 'manual(m5)', 'drv': 'f', 'cty': '21'}]
I tried 2 ways of doing this:
for d in mpg:
sum(float(d['cty']))
sum(float(d['cty']) for d in mpg)
I understand that float objects are not iterable but isn't the 2nd method just an example of list comprehension of the 1st one?
Why does the second option work but not the first?
Upvotes: 1
Views: 232
Reputation: 136
sum()
takes an iterable as an argument and sums all items of that iterable. A simple float or integer is not a list and therefore not iterable.
sum(123)
, which then returns an error.float(d['cty']) for d in mpg
in a new variable, it would create a list. If you now pass that list, the function results in sum([123, 456, 789])
, which returns the desired value.Upvotes: 3
Reputation: 134
Two ways to solve the problem:
1.
i = 0
for d in mpg:
i += float(d['cty'])
x = sum([float(d['cty']) for d in mpg])
Upvotes: 0
Reputation: 78
The second one works because the list comprehension constructs a list prior to trying to evaluate the sum, but the first way tries to pass float(d['cty'])
to the sum
. But that's just a float rather than an iterable (which is what sum
needs). See this modification of the first way:
lst = []
for d in mpg:
lst.append(float(d['cty']))
sum(lst)
Upvotes: 0