Different Forms of Assignment Statements in Python

Last Updated : 10 May, 2020
We use Python assignment statements to assign objects to names. The target of an assignment statement is written on the left side of the equal sign (=), and the object on the right can be an arbitrary expression that computes an object. There are some important properties of assignment in Python :-
  • Assignment creates object references instead of copying the objects.
  • Python creates a variable name the first time when they are assigned a value.
  • Names must be assigned before being referenced.
  • There are some operations that perform assignments implicitly.
Assignment statement forms :- 1. Basic form: This form is the most common form. Python3 1==
student = 'Geeks'
print(student)
OUTPUT
Geeks
2. Tuple assignment: Python3 1==
# equivalent to: (x, y) = (50, 100)
x, y = 50, 100  

print('x = ', x)
print('y = ', y)
OUTPUT
x = 50 
y = 100
When we code a tuple on the left side of the =, Python pairs objects on the right side with targets on the left by position and assigns them from left to right. Therefore, the values of x and y are 50 and 100 respectively. 3. List assignment: This works in the same way as the tuple assignment. Python3 1==
[x, y] = [2, 4]

print('x = ', x)
print('y = ', y)
OUTPUT
x = 2
y = 4
4. Sequence assignment: In recent version of Python, tuple and list assignment have been generalized into instances of what we now call sequence assignment - any sequence of names can be assigned to any sequence of values, and Python assigns the items one at a time by position. Python3 1==
a, b, c = 'HEY'

print('a = ', a)
print('b = ', b)
print('c = ', c)
OUTPUT
a = H
b = E
c = Y
5. Extended Sequence unpacking: It allows us to be more flexible in how we select portions of a sequence to assign. Python3 1==
p, *q = 'Hello'

print('p = ', p)
print('q = ', q)
Here, p is matched with the first character in the string on the right and q with the rest. The starred name (*q) is assigned a list, which collects all items in the sequence not assigned to other names. OUTPUT
p = H
q = ['e', 'l', 'l', 'o']
This is especially handy for a common coding pattern such as splitting a sequence and accessing its front and rest part. Python3 1==
ranks = ['A', 'B', 'C', 'D']
first, *rest = ranks

print("Winner: ", first)
print("Runner ups: ", ', '.join(rest))
OUTPUT
Winner: A
Runner ups: B, C, D
6. Multiple- target assignment: Python3 1==
x = y = 75

print(x, y)
In this form, Python assigns a reference to the same object (the object which is rightmost) to all the target on the left. OUTPUT
75 75
7. Augmented assignment : The augmented assignment is a shorthand assignment that combines an expression and an assignment. Python3 1==
x = 2

# equivalent to: x = x + 1
x += 1  

print(x)
OUTPUT
3
There are several other augmented assignment forms:
-=, **=, &=, etc.
Comment