3

From PEP448:

Whilst *elements, = iterable causes elements to be a list, elements = *iterable, causes elements to be a tuple. The reason for this may confuse people unfamiliar with the construct.

Well, I'm one of those people. I gave it a try:

>>> *e, = range(3)
>>> e
[0, 1, 2]

>>> e = *range(3),
>>> e
(0, 1, 2)

The former works in Python 3.4 and 3.5.

The latter only in 3.5. It is the new feature introduced by the mentioned PEP448. It is described in that PEP, no problem with that one.

However, I have never seen *elements, = iterable before. Could you please explain how it works and why it creates a list?

VPfB
  • 14,927
  • 6
  • 41
  • 75

1 Answers1

5

Yes, this is a new feature. Well it was done because of need to unpack "the rest" of list. So, take a look at the examples:

>>> a, *e = range(3)
>>> print(a, e)
0 [1, 2]

>>> a, *e, b = range(3)
>>> print(a, e, b)
0 [1] 2

Now your example:

>>> *e, = range(3)
>>> print(e)
[0, 1, 2]

is equivalent to:

>>> (*e,) = range(3)
>>> print(e)
[0, 1, 2]

So that comma is just for make it one element iterable (*e,). So python knows that "the rest" of range(3) should put into e, in that case whole value which [0, 1, 2] is.

Otherwise using:

>>> *e = range(3)
  File "<stdin>", line 1
SyntaxError: starred assignment target must be in a list or tuple

it doesn't work.

The rest explanation under that link.

turkus
  • 4,637
  • 2
  • 24
  • 28
  • Thanks. You did not answer why it creates a list, but the linked PEP3132 states it in the Specification section. – VPfB Sep 07 '16 at 07:35
  • I was following main question: ``Please explain the *elements,=iterable construct``. I will try to answer, gimmie a sec. – turkus Sep 07 '16 at 07:36