Walking lists

Jean-Michel Pichavant jeanmichel at sequans.com
Thu Feb 25 09:27:47 EST 2010


lallous wrote:
> Thank you all for the replies.
>
> The solution using Python 3's syntax look very intuitive.
>
> Thanks Tim, Arnaud for the idea (I am using 2.x)
>
> --
> Elias
> On Feb 25, 1:28 pm, lallous <elias.bachaal... at gmail.com> 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:]
>>     ....
>> Probably that is not possible, but just asking.
>>
>> Thanks,
>> Elias
>>     
Using slicing + list comprehension with python 2.x

for first, rest in [(e[0],e[1:]) for e in L]:
     print first
     print rest


1
(2, 3)
4
()
5
()
6
(7,)


But honestly, the code you provided is just fine.

JM



More information about the Python-list mailing list