4 Advanced Topic, Building lists


#1

I know this looks super simple to 99.99% of you all but I want to ask about the code below..
evens_to_50 = [i for i in range(51) if i % 2 == 0]
print evens_to_50

So far in this class I have no learned how to combine for and if in on line of code? is it this simple? just keep typing with no indentation of colon?
Also what is this "i" at the start of the list definition ?


#2

Hi @fahadfahad ,

This is a list comprehension ...

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

See Codecademy > Python > Advanced Topics in Python > 5: List Comprehension Syntax to review that topic, and see an example of combining for and in within the same line of code.


#3

Hello @fahadfahad. I'm just learning myself friend, so you don't need to feel alone!

From what I understand, this is called a list comprehension, which is basically what you were asking: a combination of for's and if's and in's and such.

Just as you would write:

num = 2

if num == 2:
    print "This is okay."
else:
    print "Oops, something is wrong!"

You would now write like shown:

[i for i in range(1,6) if i % 2 == 0]
print test

All this is checking for is as long as i is within the range of 1-6 and it is an even number, it will print.

As for your question about the i in front of everything, it is simply just the syntax for the "list comprehension".

You will catch onto it. Good luck!