Home > Software engineering >  Summing using Inline for loop vs normal for loop
Summing using Inline for loop vs normal for loop

Time:11-08

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:

  1. This gives the error that float object is not iterable.
for d in mpg:
    sum(float(d['cty']))
  1. 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?

CodePudding user response:

sum() takes a list as an argument and sums all items of that list. A simply 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 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.

CodePudding user response:

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)

CodePudding user response:

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])
  • Related