Building Lists


Hey so I am looking at a code, that is pre-given, and i don’t fully understand it.

evens_to_50 = [i for i in range(51) if i % 2 == 0]
print evens_to_50

this is supposed to print all even numbers from 0-50. I’ve never seen it done like this before, and I have a couple questions.

Why is there an i before the for loop?

Is it normal to have a for loop in one line w/ out a : ?

thank can you please keep explanations and answers as simple as possible as I am quite young.


this is list comprehension:

[i for i in range(51) if i % 2 == 0]

this would be “normal” code:

evens_to_50 = []
for i in range(51):
    if i % 2 == 0:

the i before the for in list comprehension is what you are appending to list, so its the equivalent of .append(i)


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.