Pythonification of the asterisk-based collection packing/unpacking syntax

Chris Angelico rosuav at gmail.com
Tue Dec 27 23:06:37 EST 2011


On Wed, Dec 28, 2011 at 10:10 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> Your original use-case, where you want to change the type of tail from a
> list to something else, is simply solved by one extra line of code:
>
> head, *tail = sequence
> tail = tuple(tail)

That achieves the goal of having tail as a different type, but it does
have the additional cost of constructing and then discarding a
temporary list. I know this is contrived, but suppose you have a huge
set/frozenset using tuples as the keys, and one of your operations is
to shorten all keys by removing their first elements. Current Python
roughly doubles the cost of this operation, since you can't choose
what type the tail is made into.

But if that's what you're trying to do, it's probably best to slice
instead of unpacking. Fortunately, the Zen of Python "one obvious way
to do it" doesn't stop there being other ways that work too.

ChrisA



More information about the Python-list mailing list