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 "<stdin>", 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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容