Building lists and the magic i


I was wondering why an i starts the notation in the brackets below. I found it weird because it does not have a comma after the i, which other notations seem to have. I know it's apart of the syntax so please don't give me the "just because" statement.

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


List comprehension's are something that takes a little while to fully grasp and are certainly confusing. This website does a pretty good job explaining what is going on.

To sum it up though, i is the end result, the value we ultimately want. for i in range(51) is what we are doing with i. and if i % 2 == 0 is the condition we are applying.

We could write the same statement as

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

The list comprehension is just a much simpler way to write the same thing.


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