Walking lists

Arnaud Delobelle arnodel at googlemail.com
Thu Feb 25 14:26:45 CET 2010



lallous wrote:
> Hello
>
>
> I am still learning Python, and have a question, perhaps I can shorten
> the code:
>
> L = (
>   (1, 2, 3),
>   (4,),
>   (5,),
>   (6, 7)
> )
>
> for x in L:
>     print x
>
> What I want, is to write the for loop, something like this:
>
> for (first_element, the_rest) in L:
>   print first_element
>   for x in the_rest:
>     # now access the rest of the elements
>
> I know I can :
> for x in L:
>     first = x[0]
>     rest = x[1:]

Others have replied about Python 3.  In Python 2.x, you can use an
iterator:

for tuple in L:
    it = iter(tuple)
    first = it.next()
    for x in it:
        ...

HTH

--
Arnaud



More information about the Python-list mailing list