1

If I have three variables, such as x,y,z=1,2,3, I can use x=y=z but can't use x=(y=z) in python. What's difference between x=y=z and x=(y=z)?

2 Answers 2

2

y=z is an assignment statement, not an expression (as it is in, say, C). It can only be used where a statement is expected. You can't, for instance, do print(y=z). So x=(y=z) is grammatically ill-formed.

x=y=z is a single assignment, not a combination of two assignments. The grammar specifically allows targets to be chained in an assignment statement. The relevant grammar bit:

assignment_stmt ::=  (target_list "=")+ (expression_list | yield_expression)
Sign up to request clarification or add additional context in comments.

4 Comments

assignment_stmt ::= (target_list "=")+ (expression_list | yield_expression) just has one assignment operator, why you say it can be chained?
@gaussclb: The + means "one or more" of the thing the + is attached to.
Do you mean assignment_stmt ::= (target_list "=")+ (expression_list | yield_expression | assignment_stmt)?
No, that's not the correct grammar. As userblahblah explained, the + means that there can be multiple target_list =s chained in a single expression. target_list = target_list = target_list = expression_list.
1

x=y=z assigns x and y the value stored in z.

In [133]: z = 5

In [134]: x = y = z

In [135]: x
Out[135]: 5

In [136]: y
Out[136]: 5

x=(y=z) wants to assign to x the outcome of the expression in the parenthesis. Unfortunately, the expression y=z is not evaluated this way in Python within the parenthesis.

In [137]: x=(y=z)
  File "<ipython-input-137-445a19ecd607>", line 1
    x=(y=z)
        ^
SyntaxError: invalid syntax

If on the otherhand, you were looking to assign the result of the equivalency test of "is y equal to z", then you could do so with the following:

x=(y == z)

In [138]: x = (y == z)

In [139]: x
Out[139]: True

In [140]: y
Out[140]: 5

In [141]: z
Out[141]: 5

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.