Challenge question question | SoloLearn: Learn to code for FREE!


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?

10/12/2019 2:27:41 PM


6 Answers

New Answer


a = [] for i in [1,2,3]: if i%2 == 0: a.append(i)


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.


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.


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!!


i [] for i in range(1,4): If i%2==0: Print(i)