Walrus Operator
The Walrus Operator in Python is a new assignment operator which is introduced in Python version 3.8 and higher. This operator is used to assign a value to a variable within an expression.
Syntax: a := expression
Example: In this code, we have a Python list of integers. We have used Python Walrus assignment operator within the Python while loop. The operator will solve the expression on the right-hand side and assign the value to the left-hand side operand ‘x’ and then execute the remaining code.
# a list
a = [1, 2, 3, 4, 5]
# walrus operator
while(x := len(a)) > 2:
a.pop()
print(x)
Output:
5
4
3
Assignment Operators in Python
The Python Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic, logical, and bitwise computations. The value the operator operates on is known as the Operand. Here, we will cover Different Assignment operators in Python.
Operators | Sign | Description | Syntax |
---|---|---|---|
Assignment Operator | = | Assign the value of the right side of the expression to the left side operand | c = a + b |
Addition Assignment Operator | += | Add right side operand with left side operand and then assign the result to left operand | a += b |
Subtraction Assignment Operator | -= | Subtract right side operand from left side operand and then assign the result to left operand | a -= b |
Multiplication Assignment Operator | *= | Multiply right operand with left operand and then assign the result to the left operand | a *= b |
Division Assignment Operator | /= | Divide left operand with right operand and then assign the result to the left operand | a /= b |
Modulus Assignment Operator | %= | Divides the left operand with the right operand and then assign the remainder to the left operand | a %= b |
Floor Division Assignment Operator | //= | Divide left operand with right operand and then assign the value(floor) to left operand | a //= b |
Exponentiation Assignment Operator | **= | Calculate exponent(raise power) value using operands and then assign the result to left operand | a **= b |
Bitwise AND Assignment Operator | &= | Performs Bitwise AND on operands and assign the result to left operand | a &= b |
Bitwise OR Assignment Operator | |= | Performs Bitwise OR on operands and assign the value to left operand | a |= b |
Bitwise XOR Assignment Operator | ^= | Performs Bitwise XOR on operands and assign the value to left operand | a ^= b |
Bitwise Right Shift Assignment Operator | >>= | Performs Bitwise right shift on operands and assign the result to left operand | a >>= b |
| <<= | Performs Bitwise left shift on operands and assign the result to left operand | a <<= b |
Walrus Operator | := | Assign a value to a variable within an expression | a := exp |
Here are the Assignment Operators in Python with examples.