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?

2
  • stackoverflow.com/questions/6967632/… duplicate? Commented Jan 17, 2018 at 3: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 and see what a larger group thinks. Commented Jan 17, 2018 at 12:45

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.