Is there any nice way to unpack a list of unknown size??

Arnaud Delobelle arnodel at googlemail.com
Sun Sep 14 19:45:58 CEST 2008


On Sep 14, 4:08 pm, Gary Herron <gher... at islandtraining.com> wrote:
> srinivasan srinivas wrote:
> > I want to do something like below:
>
> > 1. first, second, third, *rest = foo
>
> Python 3.0 has exactly this feature.  No current Python 2.x version has it.
>
> Gary Herron
>
> >  2. for (a,b,c,*rest) in list_of_lists:
>
> > Please suggest.
>
> > Thanks,
> > Srini
>
> >       Bring your gang together. Do your thing. Find your favourite Yahoo! group athttp://in.promos.yahoo.com/groups/
> > --
> >http://mail.python.org/mailman/listinfo/python-list

In python >= 2.4, you can define a function like this:

def truncate(iterable, n=1):
    iterator = iter(iterable)
    for i in iterator:
        if n == 0:
            yield iterator
            return
        yield i
        n -= 1

>>> a, b, c, tail = truncate([1,2,3,4,5,6], 3)
>>> a
1
>>> b
2
>>> c
3
>>> tail
<listiterator object at 0x78990>
>>> list(tail)
[5, 6]

--
Arnaud





More information about the Python-list mailing list