[Python-ideas] Unpack of sequences

Steven D'Aprano steve at pearwood.info
Fri Aug 31 03:03:45 CEST 2012

On 31/08/12 10:17, Greg Ewing wrote:
> Mike Graham wrote:
>> That being said, `a, b, c, *_ = d` or similar is probably better than
>> introducing a new way.
> It's inefficient, though, because it results in iterating
> over the remainder of the sequence and building a new sequence
> that will never be used.

And if the sequence is large, that might even matter.

I'm not being quite as dismissive as it might sound, but in practice,
this inefficiency generally does not matter. It's unlikely to be a

> There's currently no way to spell the most efficient way of
> doing this, which is simply to stop iterating and ignore the
> rest of the sequence.

For sequences:

a, b, c, d = really_long_sequence[:4]

which might not be as efficient as possible, but by estimation
it is within a factor of two of the most efficient as possible.

For iterators, use itertools.islice.

>There's also no way to unpack the
> head of an infinite sequence without slicing it first.

Surely this is the obvious way?

head = next(sequence)  # actually an iterator


More information about the Python-ideas mailing list