Tags: atime, basically, items, iterate, mylist, programming, pull, python, time
Iterate through list two items at a time
On Programmer » Python
43,760 words with 12 Comments; publish: Fri, 04 Jan 2008 10:51:00 GMT; (20078.13, « »)
Hi all,
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 - simple examples would
be:
Create this output:
1 2
3 4
5 6
Create this list:
[(1,2), (3,4), (5,6)]
I want the following syntax to work, but sadly it does not:
for x,y in myList:
print x, y
I can do this with a simple foreach statement in tcl, and if it's easy in
tcl it's probably not too hard in Python.
Thanks,
Dave
http://python.itags.org/q_python_44788.html
All Comments
Leave a comment...
- 12 Comments

- On Jan 2, 7:57 pm, "Dave Dean" <dave.d....python.itags.org.xilinx.comwrote:Quote:=== Original Words ===Hi all,
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...
def pair_list(list_):
return[list_[i:i+2] for i in xrange(0, len(list_), 2)]
#1; Fri, 04 Jan 2008 10:53:00 GMT

- Few alternative solutions (other are possible), I usually use a variant
of the first version, inside a partition function, the second variant
is shorter when you don't have a handy partition() function and you
don't want to import modules, and the forth one needs less memory when
the data is very long:
from itertools import izip, islice
data = [1,2,3,4,5,6,7]
for x1, x2 in (data[i:i+2] for i in xrange(0, len(data)/2*2, 2)):
print x1, x2
for x1, x2 in zip(data[::2], data[1::2]):
print x1, x2
for x1, x2 in izip(data[::2], data[1::2]):
print x1, x2
for x1, x2 in izip(islice(data,0,None,2), islice(data,1,None,2)):
print x1, x2
Bye,
bearophile
#2; Fri, 04 Jan 2008 10:54:00 GMT

- Quote:=== Original Words ===>>zip(string.letters[::3], string.letters[1::3], string.letters[2::3])

