Python has two operators for equality comparison, “is” and “==” (equal to). In this article, I will teach you the difference between them and illustrate when to use them through a few simple examples.
1. The Difference Between is and == In Python.
- ==: Detects whether two Python objects values are equal.
- is: Compare whether two Python objects are the same.
2. Python is & == Example.
- In this example, the list variable a is the same as the list variable b, the two variables’ values are the same, and the two variables also point to the same python object.
>>> a = [1, 2, 3] >>> b = a >>> >>> a [1, 2, 3] >>> b [1, 2, 3] >>> # a and b has the same value. >>> a == b True # a and b point to the same python list object. >>> a is b True >>>
- If we create another list variable c based on the list variable a, then variable a and c‘s values are the same, but they point to the different python objects.
>>> a = [1, 2, 3] >>> >>> c = list(a) >>> # variable a and c's value is equal. >>> a == c True # but they point to different python list objects. >>> a is c False >>> a [1, 2, 3] >>> c [1, 2, 3] >>>