Python Assignment Operators


Assignment Operators in Python

Assignment operators in Python are used to assign values to variables. While the basic assignment operator is =, there are also compound assignment operators that combine an operation with assignment, allowing for more concise code.

Basic Assignment Operator

  • =: The basic assignment operator assigns the value on the right to the variable on the left.

Example of Basic Assignment

x = 10 print(x) # Output: 10

Compound Assignment Operators

These operators perform an operation on the variable and then assign the result back to that variable.

OperatorDescriptionExampleEquivalent to
+=Adds the right operand to the left operand and assigns the result to the left operandx += 5x = x + 5
-=Subtracts the right operand from the left operand and assigns the result to the left operandx -= 3x = x - 3
*=Multiplies the left operand by the right operand and assigns the result to the left operandx *= 2x = x * 2
/=Divides the left operand by the right operand and assigns the result to the left operandx /= 4x = x / 4
%=Performs modulus operation and assigns the result to the left operandx %= 3x = x % 3
**=Raises the left operand to the power of the right operand and assigns the result to the left operandx **= 2x = x ** 2
//=Performs floor division and assigns the result to the left operandx //= 3x = x // 3

Examples of Compound Assignment Operators

1. Addition Assignment (+=)

x = 10 x += 5 # Equivalent to x = x + 5 print(x) # Output: 15

2. Subtraction Assignment (-=)

x = 10 x -= 3 # Equivalent to x = x - 3 print(x) # Output: 7

3. Multiplication Assignment (*=)

x = 4 x *= 2 # Equivalent to x = x * 2 print(x) # Output: 8

4. Division Assignment (/=)

x = 20 x /= 4 # Equivalent to x = x / 4 print(x) # Output: 5.0 (result is a float)

5. Modulus Assignment (%=)

x = 10 x %= 3 # Equivalent to x = x % 3 print(x) # Output: 1

6. Exponentiation Assignment (**=)

x = 3 x **= 2 # Equivalent to x = x ** 2 print(x) # Output: 9

7. Floor Division Assignment (//=)

x = 10 x //= 3 # Equivalent to x = x // 3 print(x) # Output: 3

Using Assignment Operators with Other Data Types

Example with Lists

You can use the += operator to append elements to a list.

my_list = [1, 2, 3] my_list += [4, 5] # Equivalent to my_list = my_list + [4, 5] print(my_list) # Output: [1, 2, 3, 4, 5]

Example with Strings

You can also use += to concatenate strings.

text = "Hello" text += " World!" # Equivalent to text = text + " World!" print(text) # Output: "Hello World!"

Summary of Assignment Operators:

  • =: Basic assignment operator.
  • +=: Adds and assigns.
  • -=: Subtracts and assigns.
  • *=: Multiplies and assigns.
  • /=: Divides and assigns (result is a float).
  • %=: Modulus and assigns.
  • **=: Exponentiation and assigns.
  • //=: Floor division and assigns.

These assignment operators help to simplify your code by combining operations with assignment in a more concise manner.