+ 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?

12th Oct 2019, 2:27 PM
GeoK68
GeoK68 - avatar
4 odpowiedzi
+ 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.
12th Oct 2019, 3:17 PM
Qasem
+ 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.
12th Oct 2019, 3:25 PM
Lothar
Lothar - avatar
+ 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!!
12th Oct 2019, 7:07 PM
GeoK68
GeoK68 - avatar
0
i [] for i in range(1,4): If i%2==0: Print(i)
13th Oct 2019, 6:58 PM
Akash Pawar
Akash Pawar - avatar