KnowledgeBoat Logo

Computer Science

Write equivalent for loop for the following list comprehension :

gen = (i/2 for i in [0, 9, 21, 32])
print(gen)

Linear Lists

1 Like

Answer

In the above code, Python would raise an error because round brackets are used in list comprehension. List comprehensions work with square brackets only.

Explanation

The corrected code is:

gen = [i/2 for i in [0, 9, 21, 32]]
print(gen)

The equivalent for loop for the above list comprehension is:

gen = []
for i in [0, 9, 21, 32]:
    gen.append(i/2)
print(gen)

Answered By

1 Like


Related Questions