11

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
fedorqui
  • 275,237
  • 103
  • 548
  • 598
user1486654
  • 111
  • 1
  • 1
  • 4

14 Answers14

25

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!

Community
  • 1
  • 1
Erty Seidohl
  • 4,487
  • 3
  • 33
  • 45
6

The following sample should solve your problem.

Newlist = []
for x in numList:
   if x % 2 == 0:
      print x          
      Newlist.append(x)
octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131
8bitwide
  • 2,071
  • 1
  • 17
  • 24
  • This is if you want to print all the even numbers - if you want to get a list that you can work with, see the answers below. Edit: I see the new version appends it to a new list :) – Erty Seidohl Jun 27 '12 at 19:20
4

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)
David Webb
  • 190,537
  • 57
  • 313
  • 299
3

In your specific case my_list[1::3] will work. There are always two odd integers between even integers in fibonacci: even, odd, odd, even, odd, odd.....

>>> my_list = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368]
>>>         
... 
>>> my_list[1::3]
[2, 8, 34, 144, 610, 2584, 10946, 46368]
Akavall
  • 82,592
  • 51
  • 207
  • 251
2

Just check this

A = [i for i in range(101)]
B = [x for x in A if x%2 == 0]
print B
tharkay
  • 5,913
  • 2
  • 26
  • 33
Ankit Vyas
  • 47
  • 1
1

iterate through the list and use the modulo operator to check even

for number in list:
    if (number % 2) == 0: 
        ##EVEN
barbiepylon
  • 891
  • 7
  • 23
0

You can use list comprehension to generate a new list that contains only the even members from your original list.

data = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]

then:

new_data = [i for i in data if not i%2]

yields

[2, 8, 34, 144]

Or alternatively use a generator expression if you don't need all of the numbers at once:

new_data = (i for i in data if not i%2)

The values then would be availabe as needed, for instance if you used a for loop:

e.g.,

for val in new_data:
   print val

The advantage of the generator expression is that the whole list is not generated and stored in memory at once, but values are generated as you need them which makes less demand on memory. There are other important differences you might want to read up on at some point if you are interested.

Levon
  • 138,105
  • 33
  • 200
  • 191
0

Just for fun, checking if number%2 != 1 also works ;)

evens=[x for x in evens_and_odds if number%2 != 1 ]

Note that you can do some clever things to separate out evens and odds in one loop:

evens=[]
odds=[]
numbers=[ evens, odds ]
for x in evens_and_odds:
    numbers[x%2 == 1].append(x)

print evens
print odds   

The above trick works because logical expressions (==, >, etc.) operating on numbers True (1) and/or False (0).

mgilson
  • 300,191
  • 65
  • 633
  • 696
0

Instead of generating all Fibonacci numbers then filtering for evens, why not generate just the even values?

def even_fibs():
    a,b = 1,2
    while True:
        yield b
        a,b = a+2*b, 2*a+3*b

generates [2, 8, 34, 144, 610, 2584, 10946 ...]

then your sum code becomes:

total = 0
for f in even_fibs():
    if f >= 4000000:
        break
    else:
        total += f

or

from itertools import takewhile
total = sum(takewhile(lambda n: n<4000000, even_fibs()))
Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99
0
a = range(0,1000)
b = []
for c in a:
    if c%2==0:
        b.append(c)
print b
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • 1
    It would be nice if you included some information regarding what this does. Also, you could save a lot of code using the third `step` argument to `range`. – jonrsharpe Jul 31 '14 at 10:14
0

You could do this using the filter function as follows:

F = [1, 2]
while F[-1] < 4000000:
    F.append(F[-1] + F[-2])
print(F)
print('\n')
#create the variable that could store the sorted values from the list you have created.
sorted_number=list(filter(lambda x:x%2==0,F))
print(sorted_number)
0

You could use a for and if loop using the length function, like this:

for x in range(len(numList)):
    if x%2 == 0:
        print(x)
        NewList.append(x)
Adeesh Jain
  • 119
  • 5
0

Basically you should create a variable and put your list in and then sort your even numbers list by adding it only the even numbers

numbers = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, ...] even = [e for e in numbers if e%2==0]

gxet4n
  • 349
  • 6
  • 11
0

Here are some of the different ways to get even numbers:

CASE 1 in this case, you have to provide a range

lst = []
for x in range(100):
    if x%2==0:
    lst.append(x)
print(lst)

CASE 2 this is a function and you have to pass a parameter to check if it is an even no or not def even(rangeno): for x in range(rangeno): if rangeno%2 == 0: return rangeno else: return 'No an Even No'

 even(2)

CASE 3 checking the values in the range of 100 to get even numbers through function with list comprehension

def even(no):
return [x for x in range(no) if x%2==0]

even(100)

CASE 4 This case checks the values in list and prints even numbers through lambda function. and this case is suitable for the above problem

lst = [2,3,5,6,7,345,67,4,6,8,9,43,6,78,45,45]
no = list(filter(lambda x: (x % 2 == 0), lst))
print(no)
Jahanzeb Nawaz
  • 1,128
  • 12
  • 11