Can I use += on multiple variables on one line?

3.3k Views Asked by At

While shortening my code I was cutting down a few variable declarations onto one line-

##For example- going from-
Var1 =15
Var2 = 26
Var3 = 922

##To-
Var1, Var2, Var3 = 15, 26, 922

However, when I tried doing the same thing to this code-

User_Input += Master_Key[Input_ref]
Key += Master_Key[Key_ref]
Key2 += Master_Key[Key_2_Ref]

##Which looks like-
User_Input, Key, Key2 += Master_Key[Input_Ref], Master_Key[Key_Ref], Master_Key[Key_2_Ref]

This throws the error

SyntaxError: illegal expression for augmented assignment

I have read the relevant Python documentation, but I still can't find a way to shorten this particular bit of code.

1

There are 1 best solutions below

2
On BEST ANSWER

No, you cannot. You cannot use augmented assignment together with multiple targets.

You can see this in the Augmented assignment statements section you linked to:

augmented_assignment_stmt ::=  augtarget augop (expression_list | yield_expression)
augtarget                 ::=  identifier | attributeref | subscription | slicing

The augtarget rule only allows for one target. Compare this with the Assignment statements rules:

assignment_stmt ::=  (target_list "=")+ (expression_list | yield_expression)
target_list     ::=  target ("," target)* [","]
target          ::=  identifier
                     | "(" target_list ")"
                     | "[" target_list "]"
                     | attributeref
                     | subscription
                     | slicing

where you have a target_list rule to assign to.

I'd not try and shorten this at all; trying to squeeze augmented assignments onto one line does not improve readability or comprehension of what is happening.