Walking lists
Tim Chase
python.list at tim.thechases.com
Thu Feb 25 08:02:49 EST 2010
lallous wrote:
> L = (
> (1, 2, 3),
> (4,),
> (5,),
> (6, 7)
> )
>
> 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
Python 3 introduced a variable tuple assignment which I
suspect[*] would work in this context:
for first, *rest in L: # note the asterisk
print first
for x in rest:
do_stuff(x)
> I know I can :
> for x in L:
> first = x[0]
> rest = x[1:]
However in 2.x, this is the way to do it. Though if you want to
abstract the logic, you can move it to a generator:
def splitter(i):
for t in i:
yield t[0], t[1:]
for first, rest in splitter(L):
print first
for x in rest:
do_stuff(x)
-tkc
[*] not having py3 on this machine, I can't readily verify this.
More information about the Python-list
mailing list