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 :-
Python3 1==
OUTPUT
Python3 1==
OUTPUT
Python3 1==
OUTPUT
Python3 1==
OUTPUT
Python3 1==
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
Python3 1==
OUTPUT
Python3 1==
In this form, Python assigns a reference to the same object (the object which is rightmost) to all the target on the left.
OUTPUT
Python3 1==
- 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.
student = 'Geeks'
print(student)
Geeks2. Tuple assignment:
# equivalent to: (x, y) = (50, 100)
x, y = 50, 100
print('x = ', x)
print('y = ', y)
x = 50 y = 100When 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.
[x, y] = [2, 4]
print('x = ', x)
print('y = ', y)
x = 2 y = 44. 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.
a, b, c = 'HEY'
print('a = ', a)
print('b = ', b)
print('c = ', c)
a = H b = E c = Y5. Extended Sequence unpacking: It allows us to be more flexible in how we select portions of a sequence to assign.
p, *q = 'Hello'
print('p = ', p)
print('q = ', q)
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.
ranks = ['A', 'B', 'C', 'D']
first, *rest = ranks
print("Winner: ", first)
print("Runner ups: ", ', '.join(rest))
Winner: A Runner ups: B, C, D6. Multiple- target assignment:
x = y = 75
print(x, y)
75 757. Augmented assignment : The augmented assignment is a shorthand assignment that combines an expression and an assignment.
x = 2
# equivalent to: x = x + 1
x += 1
print(x)
OUTPUT
3There are several other augmented assignment forms:
-=, **=, &=, etc.