Skip to content
Advertisement

How to change the for loop to list comprehension?

In the following code snippet:

from collections import OrderedDict

data = [OrderedDict([('sale', '143017'), ('profit', '345'), ('quantity', '45')]),
        OrderedDict([('sale', '243215'), ('profit', '400'), ('quantity', '105')]),
        OrderedDict([('sale', '98342'), ('profit', '100'), ('quantity', '55')])]

sale_list = []
for i in range(2):
    sale_list.append(list(data[i].items())[0][1])

print(sale_list)

The output is:

['143017', '243215']

I wonder how to change the for loop to a list comprehension?

Advertisement

Answer

from collections import OrderedDict

data = [OrderedDict([('sale', '143017'), ('profit', '345'), ('quantity', '45')]),
    OrderedDict([('sale', '243215'), ('profit', '400'), ('quantity', '105')]),
    OrderedDict([('sale', '98342'), ('profit', '100'), ('quantity', '55')])]


sale_list = [ list(data[i].items())[0][1] for i in range(2) ]

print(sale_list)

This should work, here is a basic example

h_letters = []

for letter in 'human':
    h_letters.append(letter)

print(h_letters)

Would instead be

h_letters = [ letter for letter in 'human' ]
print( h_letters)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement