34

Possible Duplicate:
Python program to split a list into two lists with alternating elements

Problem

Given a list like this:

list1 = [blah, 3, haha, 2, pointer, 1, abcd, fire]

I expect to get this output:

list = [3, 2, 1, fire]

So what I want is to make a list of even elements of the former list.

What I tried

I tried using a for statement and tried to delete 2nd element while appending them to the list, but it didn't work out:

count = 0
for a in list1:
 list2.append(a)
 if count % 2 = = 1:
  list2.pop(count)

print list2
Anonymous
  • 835
  • 1
  • 5
  • 21
H.Choi
  • 3,095
  • 7
  • 26
  • 24

3 Answers3

62

You can use list slicing. The following snippet will do.

list1 = ['blah', 3, 'haha', 2, 'pointer', 1, 'poop', 'fire']
listOdd = list1[1::2] # Elements from list1 starting from 1 iterating by 2
listEven = list1[::2] # Elements from list1 starting from 0 iterating by 2
print listOdd
print listEven

Output

[3, 2, 1, 'fire']
['blah', 'haha', 'pointer', 'poop']
Diego Allen
  • 4,623
  • 5
  • 30
  • 33
47

This should give you what you need - sampling a list at regular intervals from an offset 0 or 1:

>>> a = ['blah', 3,'haha', 2, 'pointer', 1, 'poop', 'fire']
>>> a[0:][::2] # even
['blah', 'haha', 'pointer', 'poop']
>>> a[1:][::2] # odd
[3, 2, 1, 'fire']

Note that in the examples above, the first slice operation (a[1:]) demonstrates the selection of all elements from desired start index, whereas the second slice operation (a[::2]) demonstrates how to select every other item in the list.

A more idiomatic and efficient slice operation combines the two into one, namely a[::2] (0 can be omitted) and a[1::2], which avoids the unnecessary list copy and should be used in production code, as others have pointed out in the comments.

milancurcic
  • 6,202
  • 2
  • 34
  • 47
  • 1
    thank you very much :) i didn't know this kind of thing existed! it really helped – H.Choi Jul 28 '12 at 15:57
  • 1
    @H.Choi: this is covered very early in every tutorial, including [the official one](http://docs.python.org/tutorial/). You're going to be missing out on a lot of cool stuff if you don't read one.. – DSM Jul 28 '12 at 16:03
  • 17
    Why `[0:][::2]` and `[1:][::2]` instead of `[::2]` and `[1::2]`? This will copy the list unnecessarily. – senderle Jul 28 '12 at 16:30
  • 4
    -1 with this syntax. It is unnecessary and non-ideomatic. Use the idiomatic Python slice `[::2]` for even and `[1::2]` for odd. – dawg Jul 28 '12 at 16:53
  • I think the answer below is easier to understand. Combining two concepts in one answer confused me. – Ray Salemi May 24 '19 at 18:20
5

You can just slice the list: For odd : a[1::2] For even : a[::2]

Arsh Singh
  • 2,038
  • 15
  • 16