looping throuhg a list 2 items at a time

Cliff Wells logiplexsoftware at earthlink.net
Wed Apr 10 18:55:45 EDT 2002


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
> 
> liter = iter(l)
> for i in l:
>   print i, liter.next()
> 
> But I get:
> 
> 1 1
> s s
> 2 2
> t t
> 3 3
> d d
> 
> whereas I want
> 
> 1 s
> 2 t
> 3 d
> 
> I can see I'm wrong - any ideas on how to fix it?

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. 

Regards,

-- 
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 x308  (800) 735-0555 x308





More information about the Python-list mailing list