tags:

views:

153

answers:

5

Say I have a list that looks like this:

['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9', 'item10']

Using Python, how would I grab pairs from it, where each item is included in a pair with both the item before and after it?

['item1', 'item2']
['item2', 'item3']
['item3', 'item4']
['item4', 'item5']
['item5', 'item6']
['item6', 'item7']
['item7', 'item8']
['item8', 'item9']
['item9', 'item10']

Seems like something i could hack together, but I'm wondering if someone has an elegant solution they've used before?

+1  A: 

This should do the trick:

[(foo[i], foo[i+1]) for i in xrange(len(foo) - 1)]
Hank Gay
Indeed it does, bravo! I knew there was something I could do with a list comprehension, but just wasn't sure how to approach it. Thanks!
t3k76
this produces tuples not lists as the OP asked for
joaquin
The OP actually only asked for pairs, but if you would prefer a list over a tuple, you just change to `[foo[i], foo[i+1]]` in the comprehension.
Hank Gay
what about foo[i:i+1]? I'd think that may be faster.
phkahler
That doesn't actually work because [a:b] indexes from a to b-1, which only results in one number. This does work:[foo[i:i+2] for x in xrange(len(foo) - 1)]
Jonathan Sternberg
+11  A: 

A quick and simple way of doing it would be something like:

a = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9', 'item10']

print zip(a, a[1:])

Which will produce the following:

[('item1', 'item2'), ('item2', 'item3'), ('item3', 'item4'), ('item4', 'item5'), ('item5', 'item6'), ('item6', 'item7'), ('item7', 'item8'), ('item8', 'item9'), ('item9', 'item10')]
Simon Callan
Even more compact than the list comprehension. I've never even seen zip before.
t3k76
Very nice. I didn't realize that zip would effectively reduce down the list like that.
Hank Gay
A: 
>>>a = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9', 'item10']
>>>[[a[i],a[i+1]] for i in range(len(a)-1)]

[['item1', 'item2'], ['item2', 'item3'], ['item3', 'item4'], ['item4', 'item5'], ['item5', 'item6'], ['item6', 'item7'], ['item7', 'item8'], ['item8', 'item9'], ['item9', 'item10']]
joaquin
+3  A: 

Check out the pairwise recipe in the itertools documentation.

Mike Graham
A: 

this is also do the trick:

list_of_tupples = map(None,the_list[::2], the_list[1::2])
idog