+ 4
Challenge question question
I came across this line of code in a challenge: a = [i for i in range(1,4) if i%2==0] I understand what the line does, but having difficulty understanding the section âi for i in rangeâ. My initial thought is that âfor i in rangeâ should perform the task, but that gets an invalid syntax error. Can someone please help with the logic?
6 Answers
+ 5
This form is named list comprehension and is a special syntax in python. I mean you should memorize it as it exists:
[Variable; for variable in iterable; conditions]
Note that semicolon is for showing different sections not in the syntax.
+ 5
This is a list comprehension:
a = [i for i in range(1,4) if i%2==0]
There is a for loop which gets input from a range object, namely numbers from 1 up to 3. Content of *for loop var i* will be appended to *list a*, but only if it's an even number. This is checked with *if i%2==0*. So result is 2, as this is the only even number in the defined range.
+ 4
That helps to also explain why the scope of i is within the list comprehension. Once outside the variable no longer exists!
Thank you for the helpful explanations!!
0
i []
for i in range(1,4):
If i%2==0:
Print(i)