Home > Article > Backend Development > What is the python assignment statement?
Assignment statement
In Python, the main assignment operator is the equal sign (=)
Assignment does not directly assign a value to a variable. Objects are passed by reference. Regardless of whether the variable is newly created or already exists, a reference to the object is assigned to the variable.
In C language, the assignment statement can be regarded as an expression and can return a value. But in Python, assignment statements do not return values. This makes such a statement illegal
>>> y = (x = x + 1) # assignments not expressions! File "<stdin>", line 1y = (x = x + 1)^SyntaxError: invalid syntax>>> if (a = 3): SyntaxError: invalid syntax
Compared to ordinary assignment, it is not just a change in writing, the most significant change is that the first object is only processed once.
Python does not support pre/post increment/decrement operations such as x or --x
Multiple assignment
>>> x, y, z = 1, 2, 'a string'>>> x1 >>> y2 >>> z'a string'>>> x, y, z (1, 2, 'a string')
When assigning, the objects on both sides of the equal sign They are all regarded as tuples
Using the method of multiple assignment, you can directly exchange table values without using intermediate variables
>>> x , y = 1, 2 >>> x, y (1, 2)>>> x, y = y, x>>> x, y (2, 1)
The following table is the copy operation and annotation
Operation | Explanation |
a=10 | Basic form |
a,b = 10,20 | Tuple assignment |
[a,b] = [10,20] | List assignment( Positional) |
a,b = 'AB' | Sequence assignment (general) |
a,b = [10,20] | Sequence assignment (generality) |
a,*b = 'hello' | Extended sequence unpacking (python3 Unique to medium) |
a = b = c = 10 | Multiple target assignment |
a = 1 | Enhanced assignment |
The above is the detailed content of What is the python assignment statement?. For more information, please follow other related articles on the PHP Chinese website!