This article will discuss the difference between “in” and “is” keywords in Python.
The “in” keyword
The in operator is a membership operator. In other words, It checks whether an element exists in a sequence. The in operator will return “True” if the element is found in the sequence.
<element> in <sequence>
>>> name = "nolowiz" >>> "w" in name True >>> fruits = ["apple","orange","mango"] >>> "apple" in fruits True >>> "Avocado" in fruits False >>> odd_numbers = [1,5,7,9] >>> 5 in odd_numbers True
We can see that the in keyword is used to test if a sequence (list, tuple, strings, etc) contains a value. If the value is present in the sequence it will return “True” otherwise it will return “False”.
Another use of in keyword is it is used to traverse the sequence using for loop.
for letter in "nolowiz": print(letter)
n o l o w i z
The “is” keyword
The Python is keyword is an identity check. The “is” keyword is used to test if two variables refer to the same object in memory. It returns “True” if two objects are identical.Most of the time we’ll use it to check if an object is None.
<object1> is <object2>
>>> a = [1,2] >>> b = [1,2] >>> a is b False
Here we can see that even though the variable “a” and “b” contents are the same ([1,2]), they are different objects in memory.
>>> a = [1,2] >>> b = [1,2] >>> a is b False >>> c = a >>> c is a True
Here variable “a” is assigned to variable “c” now “c” and “a” are identical objects.
If check the equality == it will return True because the contents are the same.
>>> a == b True >>> a is b False
In conclusion, the in keyword is used to check the membership of an element in a sequence. The is the keyword to check if two objects are the same.