Python 2.7 - unpacking an iterative object throws a syntax error

I am learning python and I have a simple list like this

z = [1,2,3,4,5,6,7,8,9]

and I'm just trying to unpack it, which causes a syntax error.

a,*b,c = z
>>> a,*b,c = z
  File "<stdin>", line 1
    a,*b,c = z
      ^
SyntaxError: invalid syntax

I also tried to change the order of the variable, but the same error. Any suggestions pls.

+4
source share
2 answers

Here is a quote from PEP-3132

For example, if seq is a slicable sequence, all of the following assignments are equivalent if seq has at least three elements:

a, b, c = seq[0], list(seq[1:-1]), seq[-1]
a, *b, c = seq
[a, *b, c] = seq

In Python2.7, only the first version is legal syntax.

Since you already know what zis a list, you can simply write

a, b, c = z[0], z[1:-1], z[-1]

This will work for Python2.7 and Python3.x

+3

, , Python2, - .

>>> z = [1,2,3,4,5,6,7,8,9]
>>> a, b, c = z[0], z[1:-1], z[-1]
>>> a
1
>>> b
[2, 3, 4, 5, 6, 7, 8]
>>> c
9

Python3, :

:

>>> z = [1,2,3,4,5,6,7,8,9]
>>> a, *b, c = z
>>> a
1
>>> b
[2, 3, 4, 5, 6, 7, 8]
>>> c
9
>>> *a, b, c = z
>>> a
[1, 2, 3, 4, 5, 6, 7]
>>> b
8
>>> c
9
>>> *a, *b, c = z
  File "<stdin>", line 1
SyntaxError: two starred expressions in assignment

Python3.5

>>> [1, 2, *[3, 4]]
[1, 2, 3, 4]
+3

Source: https://habr.com/ru/post/1624199/


All Articles