Python Membership and Identity Operators

Python Membership and Identity Operators

In Python, operators are special symbols used to operate on variables and values. Among them, membership and identity operators are two special categories that assist in checking relationships between variables and data structures. They are crucial in conditional statements, loops, and object-oriented programming. In this article, you will understand what membership and Identity operators are, how they work, and how to implement them using some real-world examples.

Table of Contents:

What are Membership Operators in Python?

Membership operators are operators in Python that are used to check whether a value exists in a sequence or not. These operators are used to check the value in strings, tuples, sets, or dictionaries. If the value is found, then the True Boolean value is returned; Otherwise, the False Boolean value is returned. 

Types of Membership Operators in Python

In Python, we have two membership operators, in and not in.

OperatorDescription
inReturns True if a value is found in a sequence
not inReturns True if a value is not found in a sequence

‘in’ operator in Python

The ‘in’ operator in Python looks for the presence of the value in the sequence. It returns True if the value is present and False if it is not.

Value found: True

Value not found: False

‘not in’ operator in Python

The not in operator checks if a value is not present in a sequence or collection. If the value is absent, it returns True otherwise, False. It works in the exact opposite way to the in operator.

Value not found: True

Value found: False

Examples of Membership Operators with Different Data Types in Python

There are five major data types in Python where membership operators are applicable. These are lists, tuples, dictionaries, strings, and sets. We will look at one example for each of these in Python. 

Lists in Python

In this code, we will check whether 20 exists in the list or not.

Example:

Python

Output: 

Lists in Python

Explanation: Since 20 was in the list, it returns True.

Tuples in Python

In this code example, we will check the existence of ‘banana’ and ‘strawberry’ in the given tuple. It will return the boolean value accordingly. 

Example:

Python

Output:

Tuples in Python

Explanation: Here, ‘banana’ is present in the tuple, whereas ‘strawberry’ is not.

Sets in Python

In this example, we will initialise a set of 10 natural numbers and validate the “absence” of 4 and 26 using the not in membership operators. 

Example:

Python

Output:

Sets in Python

Explanation: Here, since 26 was not present, it returned True for the not in membership operator, and 4 was present, hence it returned False.

Strings in Python

We will find whether the strings ‘pen’ and ‘ten’ are present in ‘penmanship’ or not, using the membership operators.

Example:

Python

Output:

Strings in Python

Explanation: Here, we used the “in” membership operator with a pen, which looks for presence. We used “not in” with “ten,” which looks for absence. Hence, both answers are true. 

Dictionary in Python

In Python, the membership operators only check for the presence of the key in dictionaries. These operators are not used with the values of key-value pairs. It returns True if the key is present and False if it is not.

Example:

Python

Output:

Dictionary in Python

Explanation: Here, the in operator checks if ‘age’ is a key in the dictionary, and since ‘age’ is indeed a key, it returns True. On the other hand, when checking if 25 is in the dictionary, the in operator looks for 25 as a key, not as a value. Since 25 is a value and not a key, the operator returns False.

What are Identity Operators in Python?

Identity Operators compare the memory location of the two objects. This operator will return True if the objects have the same memory location, and will return False if the objects are just equal in value, but not in memory location. Python manages memory dynamically. Because of this, mutable objects can share a reference to the same object. 

Knowing whether two variables refer to the same memory location helps us avoid accidentally changing the content using one of the variables when we don’t want to. Let us look at an example that demonstrates the concept of identity operators. 

Example: We have a list, ‘original_scores,’ that contains the scores of students. Now, we refer to the same list using a variable, backup_scores. If we accidentally clear backup_scores, the original_scores list will also be modified. This might lead to unintended consequences or data corruption.

Python

Output:

 Identity Operators

Explanation: As you can see, even though we did not use the original_scores variable, we modified the backup_scores variable, and it reflected in the original list as well.

Types of Identity Operators in Python

There are two types of Identity Operators in Python: is and is not. 

OperatorDescription
isReturns True if both variables point to the same object
is notReturns True if the variables point to different objects

‘is’ Operator in Python

It will return True when both the objects refer to the same memory location, or else it will return False. This is often used with singleton values like ‘None’ to check if the memory location is empty or not.

Example:

Python

Output:

is Operator in Python

Explanation: We check if the x variable has not been initialized using the is operator. Since it is True, we can initialise it to anything. 

‘is not’ Operator in Python 

This returns true if two variables do not refer to the same object in the same memory location, even if their value is the same.

Example:

Python

Output:

is not Operator in Python

Explanation: Even though both a and b have the same values and might look like they are referring to the same object, they do not. We were able to check this using the is not operator.

Difference Between Equality Operator and is Operator in Python

Equality Operator (==)is (Identity Operator)
Compare the value of two objectsCompares memory location (object identity)
True if values are equalTrue if both refer to the same object
All data types (strings, lists, numbers, etc.)Singleton objects (None, classes, caching checks)
[1, 2] == [1, 2] → True[1, 2] is [1, 2] → False
Check if the data/content is the sameCheck if two variables point to the same object

Difference Between Membership Operator and Identity Operator in Python

FeatureMembership Operators (in, not in)Identity Operators (is, is not)
PurposeCheck if an element exists in a containerCheck if two variables refer to the same object
Works onSequences and containers (list, tuple, dict, str)Any object (mutable or immutable)
ReturnsTrue or False based on presence/absenceTrue or False based on object identity
Example“a” in “apple” → Truea is b → True if a and b are the same object
Typical use-casesSearching in data, validation, and loopsComparing None, checking singleton behaviour, references

Real-World Scenarios with Examples

These examples show how membership and identity operators are applied in practical scenarios, making Python programs more efficient.

Login Authorisation Using Membership

In real applications, user authentication often involves checking if a username exists in an authorised list. The in operator simplifies this process.

Example:

Python

Output:

Login Authorisation Using Membership

Explanation: Since ‘Lithin’ was not in the authorised users list, he was denied access.

Preventing Duplicate Object Creation

In certain applications, we want to ensure that only one instance of a class is created and used throughout the program. This is known as the Singleton Pattern, often used for configuration managers, logging systems, or database connections, where having multiple instances could cause unexpected behaviour or inefficiency.

Example:

Python

Output:

Preventing Duplicate Object Creation

Explanation: Here, even though we wrote a log for logger2, it was updated for logger1 only. This happened because they were referring to the same object. We checked this using the is operator.

Conclusion

Membership and identity operators help make your Python code easier to read and work with. The membership operators ‘in’ and ‘not in’ check if a value exists in a list, set, dictionary, or string. They are useful when you want to filter data or check user input. Identity operators like is and ‘is not’ are used to compare objects, especially when working with values like None. Knowing how and when to use these operators will help you write better, cleaner, and more reliable Python code.

To take your skills to the next level, check out this Python training course and gain hands-on experience. Also, prepare for job interviews with Python interview questions prepared by industry experts.

Python Membership and Identity Operators – FAQs

Q1. What is a member operator?

A membership operator checks if a value exists within a sequence, like a list, tuple, string, or dictionary.

Q2. What is the membership operation on a string?

It checks if a substring exists within a string using in or not in.

Q3. What are identity operators in Python?

Identity operators compare whether two variables refer to the same object in memory.

Q4. Which operator is used for identity checking?

The is operator is used to check if two variables point to the same object.

Q5. What is the difference between in and is in Python?

The ‘in operator’ checks for membership within a container, while the ‘is operator’ checks if two variables refer to the same object in memory.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner