Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 669
Sandeep Silwal Avatar asked Jan 17 '18 02:01

Sandeep Silwal


1 Answers

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]
like image 129
Zero Piraeus Avatar answered Nov 15 '22 03:11

Zero Piraeus