looping throuhg a list 2 items at a time

David Eppstein eppstein at ics.uci.edu
Wed Apr 10 21:11:44 EDT 2002


In article <3CB4E282.AAD468E4 at engcorp.com>,
 Peter Hansen <peter at engcorp.com> wrote:

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

I don't know, silently dropping the last item seems like it could be 
nonobvious enough to cause trouble later.  You don't think it should at 
least have a sanity check, causing more obvious breakage if things 
aren't as expected?  Something like:

    i = 0
    while i < len(L):
        print L[i],L[i+1]
        i += 2

which will throw an exception rather than just ignoring the last item...

-- 
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