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:
- This gives the error that float object is not iterable.
for d in mpg:
sum(float(d['cty']))
- No problem with this one.
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?
>Solution :
sum() takes a list as an argument and sums all items of that list. A simple float or integer is not a list and therefore not iterable.
- In example 1, you iterate through each item of your list of dictionaries, but then only pass a single float (the float value of the current dictionary) to your function, resulting in
sum(123), which then returns an error. - In example 2, you first iterate through your whole list of dictionaries and extract the values you need into a new list. If you stored
float(d['cty']) for d in mpgin a new variable, it would create a list. If you now pass that list, the function results insum([123, 456, 789]), which returns the desired value.