looping throuhg a list 2 items at a time

Peter Hansen peter at engcorp.com
Wed Apr 10 21:10:26 EDT 2002


David Eppstein wrote:
> 
> 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.

It works perfectly, given the requirements specified.

If the customer wanted to handle lists with odd numbers of items
he would have specified the desired behaviour.  Or he will now. :-)

don't-implement-what-wasn't-asked-for-ly yr's,
-Peter



More information about the Python-list mailing list