Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Summing using Inline for loop vs normal for loop

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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?

>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 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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading