Difference between == and = in Python

In Python, both the = and == operators are used for different purposes and have distinct meanings.

= Operator in Python

The = operator is used for assignment. It assigns the value on its right-hand side to the variable on its left-hand side.

x = 10 y = "Hello"

In this example, x is assigned the value 10, and y is assigned the string "Hello".

== Operator in Python

The == operator is used for comparison. It compares the values on its left and right sides to check if they are equal.

a = 5 b = 10 result = a == b print(result) # Output: False

Here, result is False because the values of a and b are not equal.

== VS. = in Python

  1. The = operator is used for assignment.
  2. The == operator is used for value comparison.

Example illustrating the difference:

x = 10 y = 10 x = 20 # Assignment result = x == y # Comparison print(result) # Output: True (x is now 20, but x and y have the same value)

In this example, x is first assigned the value 10, then later assigned the value 20. However, the comparison x == y still evaluates to True because both x and y have the same value (10).

Conclusion

The = operator is used for assigning values to variables, while the == operator is used to compare whether two values are equal. The = operator assigns a value, whereas the == operator checks for equality.