Generating a list of EVEN numbers in Python

user1486654 picture user1486654 · Jun 27, 2012 · Viewed 48.8k times · Source

Basically I need help in generating even numbers from a list that I have created in Python:

[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, ...]

I have tried a couple different methods, but every time I print, there are odd numbers mixed in with the evens!

I know how to generate even/odd numbers if I were to do a range of 0-100, however, getting only the even numbers from the previous mentioned list has me stumped!

P.S. I've only been using python for a couple days, if this turns out to be extremely simple, thanks in advance!

EDIT: Thanks for all the replies, with your help I've gotten through this little problem. Here is what I ended up with to complete a little excercise asking to sum the even numbers of fibonacci sequence:

F = [1, 2]
while F[-1] < 4000000
    F.append(F[-1] + F[-2])

sum(F[1::3])
4613732

Answer

Erty Seidohl picture Erty Seidohl · Jun 27, 2012

Use a list comprehension (see: Searching a list of objects in Python)

myList = [<your list>]
evensList = [x for x in myList if x % 2 == 0]

This is good because it leaves list intact, and you can work with evensList as a normal list object.

Hope this helps!