Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
In Python, assignment operators are used to set values to variables. Essentially, they take the value found on their right side and place it into the variable that is on their left.
This article covers all the types of assignment operators you can use in Python. We'll look at each one by one, explaining how they work with examples. This includes operators that handle basic arithmetic like addition and multiplication, as well as those that manage more complex data manipulations involving bits.
What is the assignment operator in Python?
In Python, the assignment operator is the equal sign (`=`). It's used to give a value to a variable. For example, if you want to store the number 10 in a variable called `age`, you would write it like this:
age = 10
Here, `age` is the variable, and `10` is the value you're assigning to it using the assignment operator (`=`). This tells Python, "Hey, let's store the value 10 in a container named `age`."
Table of Python Assignment Operators
Operator
Name
Description
Syntax
+
Addition
Adds two operands together.
a + b
-
Subtraction
Subtracts the second operand from the first operand.
a - b
*
Multiplication
Multiplies two operands together.
a * b
/
Division
Divides the first operand by the second operand.
a / b
%
Modulus
Returns the remainder of dividing the first operand by the second operand.
a % b
++
Increment
Increments the value of the operand by 1.
++a or a++
--
Decrement
Decrements the value of the operand by 1.
Addition Assignment Operator
The addition assignment operator in Python is written as +=. It makes adding a value to a variable and then saving the result in that same variable straightforward. For instance, if you start with a variable x that has a value of 10, and you want to add 5 to it, you can use this operator to do it quickly. Here's how it works:
Python
Python
x = 10 # Initial value of x
x += 5 # Add 5 to x
print(x)
You can also try this code with Online Python Compiler
In this example, x += 5 is the same as writing x = x + 5. This operator saves time and makes your code look cleaner, especially when you are doing a lot of additions. It's used very often in programming, for tasks ranging from simple counters in loops to adding values in large datasets.
Subtraction Assignment Operator
The subtraction assignment operator in Python, denoted as -= , allows you to subtract a value from a variable and immediately update the variable with the new result. This operator simplifies the process of reducing the value of a variable without needing an extra step.
Example :
Python
Python
y = 20 # Initial value of y
y -= 5 # Subtract 5 from y
print(y)
You can also try this code with Online Python Compiler
In this scenario, y -= 5 effectively performs the action of y = y - 5. It's particularly useful when you need to decrease a variable incrementally, such as when tracking remaining quantities or decreasing values in a countdown. Using this operator makes your code more concise and easier to read.
Multiplication Assignment Operator
The multiplication assignment operator in Python, denoted by *= , simplifies the process of multiplying a variable by a number and then updating that variable with the result. This operator is straightforward and reduces the need for longer expressions.
Example :
Python
Python
z = 5 # Initial value of z
z *= 3 # Multiply z by 3
print(z)
You can also try this code with Online Python Compiler
In the example above, z *= 3 is equivalent to z = z * 3. This operator is particularly useful when you need to scale a variable's value, whether it's doubling a counter, increasing the size of elements in data processing, or adjusting values dynamically in simulations. It helps keep the code clean and easy to understand.
Division Assignment Operator
The division assignment operator in Python is represented by /=. It enables you to divide a variable by a number and immediately update the variable with the new value. This operator streamlines operations that involve division, making them more direct and less cluttered in your code.
Example :
Python
Python
a = 50 # Initial value of a
a /= 2 # Divide a by 2
print(a)
You can also try this code with Online Python Compiler
In this case, a /= 2 accomplishes the task of a = a / 2. It’s particularly useful in scenarios where you need to halve values, calculate averages, or adjust measurements. By using this operator, your code remains concise and straightforward, which enhances readability and maintenance.
Modulus Assignment Operator
The modulus assignment operator in Python is indicated by %=. It's used to divide one variable by another and then update the first variable with the remainder of that division. This operator is very helpful for tasks that involve finding remainders, such as determining if a number is even or odd, or distributing items evenly.
Example :
Python
Python
b = 28 # Initial value of b
b %= 10 # Divide b by 10 and save the remainder in b
print(b)
You can also try this code with Online Python Compiler
In this example, b %= 10 effectively performs the operation b = b % 10. This result of 8 is the remainder when 28 is divided by 10. The modulus assignment operator is particularly useful in loops and conditions where you need to perform actions at regular intervals or distribute resources in simulations. It keeps the code simple and focused on the task.
Floor Division Assignment Operator
The floor division assignment operator in Python, denoted by //=, is used to perform floor division on a variable by another number, then update the original variable with the result. Floor division divides the number and rounds down to the nearest whole number. This operator is particularly useful when you need precise, integer results in divisions, especially in scenarios involving counting items where fractions don't make sense.
Example :
Python
Python
c = 47 # Initial value of c
c //= 6 # Perform floor division of c by 6
print(c)
You can also try this code with Online Python Compiler
In this case, c //= 6 translates to c = c // 6, which results in 7, the largest whole number that is less than or equal to 47/6. This operator is vital in programming tasks such as grouping items, allocating resources evenly, or determining the number of times an event can occur within a given limit without exceeding it. It simplifies the code and makes the operation outcomes clear and predictable.
Exponentiation Assignment Operator
The exponentiation assignment operator in Python is represented by **=. It enables you to raise a variable to the power of another number and then update the variable with this new value. This operator is especially useful in mathematical calculations involving powers and exponential growth, such as compound interest calculations, geometric growth, or physics simulations.
Example :
Python
Python
d = 4 # Initial value of d
d **= 3 # Raise d to the power of 3
print(d)
You can also try this code with Online Python Compiler
In this example, d **= 3 performs the operation d = d ** 3. The result, 64, is what you get when you raise 4 to the third power. Using this operator makes the code more compact and easier to read, which is particularly valuable in scenarios where space and clarity are important.
Bitwise AND Assignment Operator
The bitwise AND assignment operator in Python is written as &=. It updates a variable by performing a bitwise AND operation between the original value of the variable and another value. This operator is primarily used in low-level programming where you need to manipulate individual bits of data directly. It's helpful for tasks such as setting specific bits within a variable to 0, based on the condition of corresponding bits in another number.
Example :
Python
Python
e = 12 # Binary: 1100
f = 5 # Binary: 0101
e &= f # Perform bitwise AND on e and f
print(e)
You can also try this code with Online Python Compiler
In this scenario, e &= f translates to e = e & f. This operation compares each bit of e and f and sets the bits in e to 1 only if both corresponding bits in e and f are 1; otherwise, it sets them to 0. The result is 4, which is the decimal equivalent of the binary 0100. This operator is invaluable when you need precise control over data at the bit level, such as in graphics programming, custom data compression schemes, or hardware interface programming.
Bitwise OR Assignment Operator
The bitwise OR assignment operator in Python is represented by |=. This operator updates a variable by performing a bitwise OR operation between its current value and another value. It's commonly used in programming when you need to set specific bits of a variable to 1, irrespective of their original state. This operation is useful in scenarios like combining flags or settings where each bit represents a different boolean option.
Example :
Python
Python
g = 12 # Binary: 1100
h = 5 # Binary: 0101
g |= h # Perform bitwise OR on g and h
print(g)
You can also try this code with Online Python Compiler
In this example, g |= h effectively means g = g | h. For each bit in g and h, this operation sets the bit in g to 1 if at least one of the corresponding bits is 1. The result, 13, comes from setting the second bit of 12 (which was 0) to 1, based on the corresponding bit in 5. This operator is particularly valuable in applications that require combining several conditions or characteristics into a single variable efficiently.
Bitwise XOR Assignment Operator
The bitwise XOR assignment operator in Python is denoted by ^=. This operator is used to update a variable by performing a bitwise XOR (Exclusive OR) operation with another value. The XOR operation is unique because it sets each bit to 1 only if the corresponding bits of the operands are different. This functionality is useful for tasks such as toggling bits, creating checksums, or implementing simple encryption techniques.
Example :
Python
Python
i = 12 # Binary: 1100
j = 5 # Binary: 0101
i ^= j # Perform bitwise XOR on i and j
print(i)
You can also try this code with Online Python Compiler
In this case, i ^= j translates to i = i ^ j. For each bit position, it compares bits from i and j, and sets the bit in i to 1 if only one of the bits is 1 (they must be different). The resulting value, 9, has bits set where the original bits in 12 and 5 differ. This operator is particularly helpful when you need to invert specific bits based on another bit pattern, providing a simple yet powerful tool for data manipulation.
Bitwise Right Shift Assignment Operator
The bitwise right shift assignment operator in Python is symbolized by >>=. This operator modifies a variable by shifting its bits to the right by a specified number of positions, effectively dividing the variable by a power of two for each shift. This operation is commonly used in tasks that require rapid multiplication or division by powers of two, or when you need to manipulate data at the bit level for processing or encoding tasks.
Example :
Python
Python
k = 48 # Binary: 110000
k >>= 3 # Shift the bits of k right by 3 places
print(k)
You can also try this code with Online Python Compiler
In this example, k >>= 3 means that the bits in k are shifted three places to the right. The leftmost bits are filled with zeros (assuming k is non-negative). The result, 6, shows how the original value of 48 is effectively divided by 23 or 8. This operator provides a quick and efficient way to perform divisions by powers of two, ensuring that the code remains concise and easily maintainable.
Bitwise Left Shift Assignment Operator
The bitwise left shift assignment operator in Python is indicated by <<=. This operator updates a variable by shifting its bits to the left by a specified number of places, which effectively multiplies the variable by a power of two for each shift. This is particularly useful for quickly scaling up values or manipulating binary data in applications such as graphics processing, signal processing, or any task that benefits from fast arithmetic operations.
Example :
Python
Python
m = 3 # Binary: 000011
m <<= 2 # Shift the bits of m left by 2 places
print(m)
You can also try this code with Online Python Compiler
In this example, m <<= 2 means that the bits in m are shifted two places to the left. The rightmost bits are filled with zeros. The result, 12, demonstrates how the original value of 3 is multiplied by 22 or 4. Using the bitwise left shift operator allows for efficient, clear code when performing multiplicative operations that are powers of two, enhancing both speed and readability of the code.
Walrus Operator
The Walrus operator, denoted by :=, is a newer addition to Python, introduced in version 3.8. It is designed to make it possible to assign values to variables as part of an expression. This is helpful for simplifying code that involves both performing an operation and storing its result for immediate or subsequent use.
Example :
if (n := len([1, 2, 3, 4])) > 3:
print(f"List is longer than 3 elements; actually, it's {n} elements long.")
In this scenario, the expression (n := len([1, 2, 3, 4])) assigns the length of the list [1, 2, 3, 4] to n while simultaneously evaluating whether n is greater than 3. This results in a more compact and efficient way to handle operations that would typically require multiple steps. It reduces the need for a separate line to assign the value to n before the if condition is checked. The Walrus operator is particularly useful in loops and conditions where you need to both calculate and use a value within the same statement, streamlining the code and improving readability.
Frequently Asked Questions
Can I use the Walrus operator in older versions of Python?
No, the Walrus operator := is only available from Python 3.8 onwards. If you are using an earlier version of Python, you will need to perform assignments outside of expressions.
Is it possible to use the bitwise operators with non-integer types?
Bitwise operators (&, |, ^, <<, >>) are typically used with integers. Using them with non-integer types, such as strings or floats, will result in a TypeError. They are designed to directly manipulate the bits of integers.
Why would I use the floor division assignment operator instead of the regular division operator?
The floor division assignment operator //= is used when you need the result of the division to be an integer. Regular division /= could result in a floating-point number. Floor division is especially useful in scenarios where you need to maintain integer precision, such as in loop counters or index calculations.
Conclusion
In this article, we have learned about various types of assignment operators in Python, including addition, subtraction, multiplication, division, modulus, floor division, exponentiation, and various bitwise operations. Each operator has its specific use case, which we explained with the help of practical examples. These operators enhances your ability to write concise and efficient Python code. We also introduced the Walrus operator, a useful feature from Python 3.8 that allows for assignment inside expressions.