looping throuhg a list 2 items at a time

Rajarshi Guha rxg218 at psu.edu
Wed Apr 10 19:24:56 EDT 2002


On Wednesday 10 April 2002 18:55 in comp.lang.python Cliff Wells wrote:

> On Wed, 10 Apr 2002 18:42:34 -0400
> Rajarshi Guha wrote:
> 
>> Hi,
>>   I have a list like this:  l = [1,'s', 2,'t', 3,'d']
>> 
>> I'd like to loop through the list but within the loop I want
>> the current element and the element just after it:
>> I tried this

> 
> It would be better to organize your list into tuples before you start:
> 
> l = [(1,'s'), (2,'t'), (3,'d')]
> for a, b in l:
>     print a, b
> 
> However, if that isn't feasible, you could do:
> 
> l = [1,'s', 2,'t', 3,'d']
> for i in range(0, len(l), 2):
>     print l[i], l[i+1]
> 
> This is sort of fragile: if there aren't an even number of elements the
> loop will fail.


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)

-- 
Rajarshi Guha
rajarshi at presidency.com



More information about the Python-list mailing list