0

I found this rule here,i just didn't figure out how "*" or_expr is equivalent as starred_item .If there is nothing wrong, what is it the problem that caused my code a = 8;b = 2; *(a >> b), = (1,2,3) to raise a exception,which said "SyntaxError: can't assign to operator"?

wow yoo
  • 855
  • 8
  • 26
  • 1
    What would you even want to happen with this statement? – jsbueno Dec 11 '16 at 10:39
  • That code doesn't make sense, so it's perfectly understandable that it raises `SyntaxError`. OTOH, `*a, = 1, 2, 3` is valid (in recent versions of Python). – PM 2Ring Dec 11 '16 at 10:52
  • I am studying the syntax of Python expression.I derived the rule` *(identifier ">>" identifier)` from the specificated rules, which is classified as `starred_expression`.A tuple or list can appear at the left hand side of the simple assignment, so can ` *(identifier ">>" identifier),` .but i didn't get the correct result. – wow yoo Dec 11 '16 at 10:54

1 Answers1

1

Atribution in Python - which happens with the assignment operator = or one of the augmented operators (+=, -=, ...) is actually a statement, and can't be used as part of a normal expression as in C-syntax derived Languages.

The left part of an assignment must make sense as a variable name (or a sequence of names).

The expression you are trying to use there *a >> b, = (1,2,3) (to which I admit I can't understand what you wanted to achieve) is equivalent to a sequence were the first (and only) element is *a >> b - that is nor a valid name in Python - therefore your error.

The "*a" in assignemnts mean that any lenght that "is left of" after attribution to other parts of the sequence of names are assigned to the starred name:

In [3]: *a, b = (1, 2, 3)

In [4]: a
Out[4]: [1, 2]

In [5]: b
Out[5]: 3

And that is deterministic and works whenever a * appears:

In [6]: a, b, *c, d = range(10)

In [7]: [a, b, c, d]
Out[7]: [0, 1, [2, 3, 4, 5, 6, 7, 8], 9]

And of course, if one tries to use two stars, that results in an error due to the ambiguity:

In [8]: *a, *b, c = range(5)
  File "<ipython-input-8-e75ad61b842a>", line 1
    *a, *b, c = range(5)
                        ^
SyntaxError: two starred expressions in assignment

Again, note that in no way an arbitrary expression is allowed on the left side of an attribution operator.

On non-assignemnt expressions, the * operator can be used to expand in place an iterable. Up to Python 3.5, that was only possible on function calls - now it is possible anywhere were a sequence of literals is expected:

In [9]: a = 0, *range(10, 12), 2

In [10]: a
Out[10]: (0, 10, 11, 2)
jsbueno
  • 99,910
  • 10
  • 151
  • 209
  • I knew this conclusion ,which was introduced by [PEP-3132](https://www.python.org/dev/peps/pep-3132/). – wow yoo Dec 11 '16 at 10:57
  • I find the EBNF rule of [assignment statements](https://docs.python.org/3.5/reference/simple_stmts.html#assignment-statements) ,which explained my situation and comfirmed your answer. – wow yoo Dec 11 '16 at 11:11