Why does *x, unpack map objects in python 3?

In Python 3, the following returns a map object:

map(lambda x: x**2, range(10))

If we want to turn this object into a list, we can just cast it as a list using list(mapobject) . However, I discovered through code golfing that

*x, = mapobject

makes x into a list. Why is this allowed in Python 3?


This is an example of extended iterable unpacking, introduced into Python 3 by PEP 3132:

This PEP proposes a change to iterable unpacking syntax, allowing to specify a "catch-all" name which will be assigned a list of all items not assigned to a "regular" name.

An example says more than a thousand words:

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

As usual in Python, singleton tuples are expressed using a trailing comma, so that the extended equivalent of this:

>>> x, = [1]
>>> x
1

… is this:

>>> *x, = range(3)
>>> x
[0, 1, 2]
链接地址: http://www.djcxy.com/p/53566.html

上一篇: 将一个列表解析成变量和子列表

下一篇: 为什么* x,在Python 3中解压缩映射对象?