What Is The Difference Between Is And == In Python

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.

  1. ==: Detects whether two Python objects values are equal.
  2. is: Compare whether two Python objects are the same.

2. Python is & == Example.

  1. 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
    >>>
  2. 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]
    >>>
    
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Clicky
0
Would love your thoughts, please comment.x
()
x