6

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?

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
Sandeep Silwal
  • 321
  • 5
  • 10
  • https://stackoverflow.com/questions/6967632/unpacking-extended-unpacking-and-nested-extended-unpacking duplicate? – juanpa.arrivillaga Jan 17 '18 at 03:34
  • @juanpa.arrivillaga IMO the proposed duplicate is more of a rant than a genuine question (if it were written today, I'd vote to close it as primarily opinion based). While the accepted answer is good, and does mention the `*x, = iterable` syntax, I don't think someone else looking for an answer to Sandeep's question would find it as easily there as here. Thanks for not immediately hammering it, anyway ... I'll take this to [chat](https://chat.stackoverflow.com/rooms/6/python) and see what a larger group thinks. – Zero Piraeus Jan 17 '18 at 12:45

1 Answers1

9

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]
Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160