tags:

views:

123

answers:

6

If I have a list and I want to create a list with only even values of the original list, how would I do that?

I originally have:

list1 = [1,2,3,4,5]
list2 = []
for v in list1:
    if v % 2 == 0:
        list2 += v
print list2
+7  A: 

List comprehension is the way to go:

list1 = [1,2,3,4,5]
list2 = [i for i in list1 if i%2 == 0]
print list2 # => [2, 4]
mhawke
+1  A: 
list2 = [x for x in list1 if x%2 == 0]
mjv
+3  A: 

If you want to extend an existing list2 (not necessarily initially empty):

list2.extend(v for v in list1 if v % 2 == 0)

If there's no "initial value" for list2, and you just want to build it from scratch:

list2 = [v for v in list1 if v % 2 == 0]

You'll notice that the inner part is identical -- you can use that part in different ways (inside brackets to create a new list, as argument to .extend to extend an existing list, and so forth).

Alex Martelli
+4  A: 

You can use list comprehensions:

list2 = [x for x in list1 if x % 2 == 0]
Mikael S
A: 
list2 = [i for i in list1 if not i%2]
inspectorG4dget
A: 

I find this to be the most readable solution:

list2 = filter(lambda x: x % 2 == 0: list1)

or if you have to use this function multiple times:

is_even = lambda x: x % 2 == 0

list2 = filter(is_even, list1)
Georg