looping throuhg a list 2 items at a time
David Eppstein
eppstein at ics.uci.edu
Wed Apr 10 20:10:41 EDT 2002
In article <a92hl1$1v4c at r02n01.cac.psu.edu>,
Rajarshi Guha <rxg218 at psu.edu> wrote:
> I got this code to work:
>
> liter = iter(l)
> while(1):
> try:
> print liter.next(), liter.next()
> except StopIteration:
> break
>
> Works fine - is it an efficient way to handle this situation?
> (I could arrange the data into tuples if necessary)
Does it work fine? What if the list has an odd number of items -- the
last item won't be printed.
In one situation I had a list of items that I wanted to handle three at
a time, except that, if the number of items in the list was not a
multiple of three, I wanted to handle the last two as a pair, or the
first two and last two both as pairs. I ended up writing the part that
handled pairs or triples as a separate function, calling it once for an
initial pair (if any), then having a separate loop for the triples and
final pair:
if len(L) % 3 == 1:
loopbody(L[:2])
L = L[2:]
while len(L) > 0:
loopbody(L[:3])
L = L[3:]
this worked ok in my situation but is unsatisfactory as a general
technique because all the slicing can be slow for long lists -- I guess
you could use an index into your list instead:
i = 0
while i < len(L):
print L[i:i+2]
i += 2
Unfortunately due to the non-functionalness of print, I don't see a way
of writing one print statement that will give the same results as
"print L[i],L[i+1]" without sometimes throwing an exception.
--
David Eppstein UC Irvine Dept. of Information & Computer Science
eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/
More information about the Python-list
mailing list