Even the numbers list?

How to create a list and only extract or find even numbers in this list?

Create a function even_only(l)that takes a list of integers as a single argument. the function will return a new list containing all (and only) elements of l that are evenly divided by 2. The original list of l will remain unchanged.

For examples, it even_only([1, 3, 6, 10, 15, 21, 28])should return [6, 10, 28]and even_only([1, 4, 9, 16, 25])should return [4, 16].

Prompt. Start by creating an empty list and whenever you find an even number in it, add it to your list, and then return the list at the end.

+5
source share
8 answers

"Hand":

def even_only(lst):
    evens = []
    for number in lst:
        if is_even(number):
            evens.append(number)
    return evens

Pythonic:

def even_only(iter):
    return [x for x in iter if is_even(x)]

, is_even.

+10

, , - , , 2, , .

list.append(x) .

, , modulo, , 2...

+7

( ) - , , . , , :

[x for x in your_list if (your condition)]

( ) , ( , , ).

P.S. , , , , .

+2
source

Use a function filterto make it functional:

>>> even_filter = lambda x: not x % 2
>>> result = filter(even_filter, [0, 1, 2, 3, 4])
>>> assert result == [0, 2, 4]

Edit: Updated with correct zero parity on Vincent comment.

+2
source
>>> a = [1, 3, 6, 10, 15, 21, 28]
>>> b = [i for i in a if i%2 ==0 ]
>>> b
[6, 10, 28]
>>> a
[1, 3, 6, 10, 15, 21, 28]
+2
source
>>> even_only = lambda seq : [ x for x in seq if str(x)[-1] in "02468" ]
>>> even_only([1, 3, 6, 10, 15, 21, 28])
[6, 10, 28]
+2
source

I recently got this problem and used:

list=[1,2,3,4,5,6] #whatever your list is, just a sample
evens=[x for x in list if np.mod(x,2)==0]
print evens

returns [2,4,6]

+1
source

All = (1, 3, 6, 10, 15, 21, 28] From import itertools takewhile Evenonly = takewhile (lambda x: x% 2 == 0, All) Print (list (eventually)

-1
source

All Articles