Building lists and the magic i


#1


https://www.codecademy.com/courses/python-beginner-en-KAgt5/1/1?curriculum_id=4f89dab3d788890003000096


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]


#2

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.

http://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/

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:
        evens_to_50.append(i)

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


#3

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