CBSE Class 12 Computer Science Question 50 of 68

Data Structures - I : Linear Lists — Question 6

Back to all questions
6
Question

Question 6

Write equivalent for loop for the following list comprehension :

gen = (i/2 for i in [0, 9, 21, 32])
print(gen)
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)