Python "Every Other Element" Idiom
- by Matt Luongo
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?