Iterate through list two items at a time
skip at pobox.com
skip at pobox.com
Tue Jan 2 21:49:09 EST 2007
>> I'm looking for a way to iterate through a list, two (or more) items
>> at a time. Basically...
>>
>> myList = [1,2,3,4,5,6]
>>
>> I'd like to be able to pull out two items at a time...
Dan> def pair_list(list_):
Dan> return [list_[i:i+2] for i in xrange(0, len(list_), 2)]
Here's another way (seems a bit clearer to me, but each person has their own
way of seeing things):
>>> import string
>>> string.letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> zip(string.letters[::2], string.letters[1::2])
[('a', 'b'), ('c', 'd'), ..., ('W', 'X'), ('Y', 'Z')]
It extends readily to longer groupings:
>>> zip(string.letters[::3], string.letters[1::3], string.letters[2::3])
[('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i'), ...
Obviously, if your lists are long, you can substitute itertools.izip for
zip. There's probably some easy way to achieve the same result with
itertools.groupby, but I'm out of my experience there...
Skip
More information about the Python-list
mailing list