0

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

0

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The print needs to be moved out of the loop too.
1

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

Comments

0

Probably better to use list comprehension.

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

Nice and easy!

Comments

0
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.

2 Comments

No. The OP would like to get a list of even numbers. Your code does not provide that, because you create a new list each loop.
Yes, it prints about 50 lists with one single element: [0] [2] [4] [6] [8] [10] [12] [14] [16] [18] [20] [22]...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.