Python "Every Other Element" Idiom

Posted by Matt Luongo on Stack Overflow See other posts from Stack Overflow or by Matt Luongo
Published on 2010-04-13T16:11:51Z Indexed on 2010/04/13 16:13 UTC
Read the original article Hit count: 504

Filed under:
|

Hey guys,

I feel like I spend a lot of time writing code in Python, but not enough time creating Pythonic code. Recently I ran into a funny little problem that I thought might have an easy, idiomatic solution. Paraphrasing the original, I needed to collect every sequential pair in a list. For example, given the list [1,2,3,4,5,6], I wanted to compute [(1,2),(3,4),(5,6)].

I came up with a quick solution at the time that looked like translated Java. Revisiting the question, the best I could do was

l = [1,2,3,4,5,6]
[(l[2*x],l[2*x+1]) for x in range(len(l)/2)]

which has the side effect of tossing out the last number in the case that the length isn't even.

Is there a more idiomatic approach that I'm missing, or is this the best I'm going to get?

© Stack Overflow or respective owner

Related posts about python

Related posts about idioms