4. Building Lists syntax question



Hello! i dont understand the syntax on this example, like, here:

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

why is it necessary that extra i in: i for i in range(51) ?
isnt it just enough for i in range(51) ?

thanks for the answers!


the list comprehension you are using is basically a shorthand for this: (ignoring the if condition for a moment)

even_to_50 = []
for x in range(51):

so the first x (or in your case i) is what you are appending to the list, so you need it


ohh i got it, basically that extra i in my example indicates whats is going to fill the list


yes exactly, that is like the perfect description.


awesome :slight_smile:
thanks man