I have tested in Python 2.7, the two styles are the same. My confusion is, when reading first method to generate a list, I am always a bit confused if i%2 == 0
controls if we should execute the whole loop of i in range(100)
, or i%2 == 0
is under loop of i in range(100)
. I have the confusion maybe in the past I write Java and C++, thinking methods from there.
Looking for advice how to read list generation code, normally the pattern is [<something before loop> <the loop> <something after the loop>]
, in this case "something before loop" is 1
, and "the loop" is for i in range(100)
and "something after the loop" is i%2 == 0
.
Also asking for advice if writing code in method 1 is good coding style in Python 2.7? Thanks.
a = [1 for i in range(100) if i%2 == 0]
print a
a=[]
for i in range(100):
if i%2==0:
a.append(1)
print a
Edit 1,
I also want to compare of using xrange
in an explicit loop (compare to first method of list comprehension for pros and cons), for example,
a=[]
for i in xrange(100):
if i%2==0:
a.append(1)
print a
Edit 2,
a = [1 for i in xrange(100) if i%2 == 0]