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
3
  • Only include the number in your target list if it is divisible by 2. Jun 27, 2012 at 19:11
  • 4
    What were the different methods that you tried?
    – Wooble
    Jun 27, 2012 at 19:11
  • 3
    Slightly strange you've managed to generate a Fibonacci sequence before you can filter a list... ;) Jun 27, 2012 at 19:21

14 Answers 14

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!

5
  • 1
    I think list comprehension might be a little to advanced for the first days with python... but that's just my opinion!
    – Trufa
    Jun 27, 2012 at 19:18
  • 1
    @Trufa list comprehensions are one of the best parts about python... why not introduce them early? Jun 27, 2012 at 19:18
  • Oh I agree, but this is the best practice - and it leaves him with a list object. Jun 27, 2012 at 19:19
  • I just think it would be healthier to learn the for loops ins and outs before getting into list comprehension. But again, IMHO.
    – Trufa
    Jun 27, 2012 at 19:25
  • For a cleaner code, you could simply use if not x%2 instead of if x % 2 == 0 Mar 11, 2022 at 13:03
6

The following sample should solve your problem.

Newlist = []
for x in numList:
   if x % 2 == 0:
      print x          
      Newlist.append(x)
1
  • 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 :) Jun 27, 2012 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)
3
  • OP, this is a great answer but consider that lambda is a little too advanced for the first days of python :)
    – Trufa
    Jun 27, 2012 at 19:25
  • Ugh, ifilter? Just (x for x in numbers if not x % 2) works.
    – Katriel
    Jun 27, 2012 at 19:25
  • Have added a generator expression, although I went for n % 2 == 0
    – David Webb
    Jun 27, 2012 at 19:31
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]
3
  • This case works, but because you're relying on slicing and stepping by index it's not a portable solution.
    – jathanism
    Jun 27, 2012 at 19:17
  • I see you're slicing the list, but there's two colons? What is this method called? Jun 27, 2012 at 19:18
  • 1
    @Erty -- The third number is the "stride". You start at the first element and then take every 3rd element after that.
    – mgilson
    Jun 27, 2012 at 19:19
2

Just check this

A = [i for i in range(101)]
B = [x for x in A if x%2 == 0]
print B
1

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

for number in list:
    if (number % 2) == 0: 
        ##EVEN
2
  • nah, list comprehensions are way better for this kind of thing Jun 28, 2012 at 1:28
  • agreed...I've never seen them before. They look fast and efficient! Jun 28, 2012 at 13:50
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).

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.

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()))
0
a = range(0,1000)
b = []
for c in a:
    if c%2==0:
        b.append(c)
print b
1
  • 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, 2014 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)
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]

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)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.