Python: Iterable Unpacking

  • 1
first, rest = seq[0], seq[1:]

is replace by ...

first, *rest = seq

Also, if the right-hand value is not a list, but an iterable, it has to be converted to a list before being able to do slicing; to avoid creating this temporary list, one has to resort to

it = iter(seq)
first = next(it)
rest = list(it)

for examples,

>>> seq = (1, 2, 3, 4, 5)
>>> first, *rest = seq
>>> first
1
>>> rest
[2, 3, 4, 5]


it = iter(seq)
>>> first = next(it)
>>> first
1
>>> rest = list(it)
>>> rest
[2, 3, 4, 5]

  • 2

if seq is a slicable sequence, all the following assignments are equivalent if seq has at least three elements:

a, b, c = seq[0], list(seq[1:-1]), seq[-1]
a, *b, c = seq
[a, *b, c] = seq

an example says more than one thousand words,

>>> a, *b, c = seq
>>> a
1
>>> b
[2, 3, 4]
>>> c
5

It is also an error to use the starred expression as a lone assignment target, as in

>>> *a = range(5)
  File "", line 1
SyntaxError: starred assignment target must be in a list or tuple

This, however, is valid syntax:

>>> *a, = range(5)
>>> a
[0, 1, 2, 3, 4]

read more

  • PEP 3132 -- Extended Iterable Unpacking

你可能感兴趣的:(Python: Iterable Unpacking)