Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a list of EVEN numbers in Python

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
like image 396
user1486654 Avatar asked Jun 27 '12 19:06

user1486654


4 Answers

You can do this with a list comprehension:

evens = [n for n in numbers if n % 2 == 0]

You can also use the filter function.

evens = filter(lambda x: x % 2 == 0,numbers)

If the list is very long it may be desirable to create something to iterate over the list rather than create a copy of half of it using ifilter from itertools:

from itertools import ifilter
evens = ifilter(lambda x: x % 2 == 0,numbers)

Or by using a generator expression:

evens = (n for n in numbers if n % 2 == 0)
like image 137
Dave Webb Avatar answered Oct 16 '22 10:10

Dave Webb


The following sample should solve your problem.

Newlist = []
for x in numList:
   if x % 2 == 0:
      print x          
      Newlist.append(x)
like image 43
8bitwide Avatar answered Oct 16 '22 08:10

8bitwide


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!

like image 32
Erty Seidohl Avatar answered Oct 16 '22 08:10

Erty Seidohl


Just check this

A = [i for i in range(101)]
B = [x for x in A if x%2 == 0]
print B
like image 23
Ankit Vyas Avatar answered Oct 16 '22 09:10

Ankit Vyas