looping throuhg a list 2 items at a time

Rajarshi Guha rxg218 at psu.edu
Thu Apr 11 11:35:40 EDT 2002


On Wednesday 10 April 2002 21:10 in comp.lang.python Peter Hansen wrote:

> 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. :-)

Exactly :)
My list will always have an even number of elements.

But I think the best thing to do is to simply restructure my data structures
and use tuples. Smart data structures are the way to go!

-- 
Rajarshi Guha
rajarshi at presidency.com



More information about the Python-list mailing list