简体   繁体   中英

Inserting data into a list using the for loop in Python

I'm trying to create a list of even numbers from 1-100 by using a for loop on my variable list100 .

 list100 = range(101) for num in list100: list_even = [] if num % 2 == 0: list_even.append(num) print list_even 

However, instead of getting [2,4,6,8,10,12,14 ....], I receive:

 [0] [] [2] [] [4] [] [6] . . . . 

Please help. Thank you!!

You are resetting the list at every iteration. Try:

list100 = range(101)
list_even = []   
for num in list100:
   if num % 2 == 0:
       list_even.append(num)
print list_even

though as @koffein points out in another answer,

range(2,101,2)

is more idiomatic.

This way does not use a for loop, but is actually more idiomatic, I think.

# python 2.x
print range(2, 101, 2)

# python 3.x
print(list(range(2, 101, 2)))

Probably better to use list comprehension.

listeven = [x for x in range(101) if x % 2 == 0]

Nice and easy!

list100 = range(101)
list_even = []
for num in list100:

     if num % 2 == 0:
             list_even.append(num)
     print list_even

this should work now. My fault also that i put the array inside loop so the item is resetting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM