The Wayback Machine - https://web.archive.org/web/20240906175628/https://www.geeksforgeeks.org/python-membership-identity-operators-not-not/
Open In App

Python Membership and Identity Operators

Last Updated : 07 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

There is a large set of Python operators that can be used on different datatypes. Sometimes we need to know if a value belongs to a particular set. This can be done by using the Membership and Identity Operators. In this article, we will learn about Python Membership and Identity Operators.

Python Membership Operators

The Python membership operators test for the membership of an object in a sequence, such as strings, lists, or tuples. Python offers two membership operators to check or validate the membership of a value. They are as follows:

Membership Operator

Description

Syntax

in Operator

Returns True if the value exists in a sequence, else returns False

value in sequence

not in Operator

Returns False if the value exists in a sequence, else returns True

value not in sequence

Python IN Operator

The in operator is used to check if a character/substring/element exists in a sequence or not. Evaluate to True if it finds the specified element in a sequence otherwise False.

Example 1: Checking 'g' in string since Python is case-sensitive, returns False
'g' in 'GeeksforGeeks' 
>>False

Example 2: Checking 'Geeks' in list of strings
'Geeks' in ['Geeks', 'For','Geeks']   
>>True

Example 3: Checking 3 in keys of dictionary
dict1={1:'Geeks',2:'For',3:'Geeks'}    
3 in dict1
>>True

Example 1: In this code we have initialized a list, string, set, dictionary and a tuple. Then we use membership in operator to check if the element occurs in the corresponding sequences or not.

Python
# initialized some sequences
list1 = [1, 2, 3, 4, 5]
str1 = "Hello World"
set1 = {1, 2, 3, 4, 5}
dict1 = {1: "Geeks", 2:"for", 3:"geeks"}
tup1 = (1, 2, 3, 4, 5)

# using membership 'in' operator
# checking an integer in a list
print(2 in list1)

# checking a character in a string
print('O' in str1)

# checking an integer in aset
print(6 in set1)

# checking for a key in a dictionary
print(3 in dict1)

# checking for an integer in a tuple
print(9 in tup1)

Output:

True
False
False
True
False

Example 2: Let us see the another example, but this time without using the ‘in’ operator:

Python
#  Define a function() that takes two lists
def overlapping(list1, list2):

    c = 0
    d = 0
    for i in list1:
        c += 1
    for i in list2:
        d += 1
    for i in range(0, c):
        for j in range(0, d):
            if(list1[i] == list2[j]):
                return 1
    return 0


list1 = [1, 2, 3, 4, 5]
list2 = [6, 2, 8, 9]
if(overlapping(list1, list2)):
    print("overlapping")
else:
    print("not overlapping")

Output

overlapping

Time Complexity:

The execution speed of the ‘in’ operator depends on the target object’s type.

  • List: O(n), it becomes slower as the number of elements increases.
  • Sets: O(1), it does not depend on the number of elements.

For dictionaries, the keys in the dictionary are unique values like set. So the execution is same as the set. Whereas the dictionary values can be repeated as in a list. So the execution of ‘in’ for values() is same as lists.

Python NOT IN Operator

The ‘not in’ Python operator evaluates to true if it does not find the variable in the specified sequence and false otherwise.

Example: In this code we have initialized a list, string, set, dictionary and a tuple. Then we use membership ‘not in’ operator to check if the element occurs in the corresponding sequences or not.

Python
# initialized some sequences
list1 = [1, 2, 3, 4, 5]
str1 = "Hello World"
set1 = {1, 2, 3, 4, 5}
dict1 = {1: "Geeks", 2:"for", 3:"geeks"}
tup1 = (1, 2, 3, 4, 5)

# using membership 'not in' operator
# checking an integer in a list
print(2 not in list1)

# checking a character in a string
print('O' not in str1)

# checking an integer in aset
print(6 not in set1)

# checking for a key in a dictionary
print(3 not in dict1)

# checking for an integer in a tuple
print(9 not in tup1)

Output:

False
True
True
False
True

The operators.contains() Method

An alternative to Membership ‘in’ operator is the contains() function. This function is part of the Operator module in Python. The function take two arguments, the first is the sequence and the second is the value that is to be checked.

Syntax: operator.contains(sequence, value)

Example: In this code we have initialized a list, string, set, dictionary and a tuple. Then we use operator module’s contain() function to check if the element occurs in the corresponding sequences or not.

Python
# import module
import operator

# using operator.contain()
# checking an integer in a list
print(operator.contains([1, 2, 3, 4, 5], 2))

# checking a character in a string
print(operator.contains("Hello World", 'O'))

# checking an integer in aset
print(operator.contains({1, 2, 3, 4, 5}, 6))

# checking for a key in a dictionary
print(operator.contains({1: "Geeks", 2:"for", 3:"geeks"}, 3))

# checking for an integer in a tuple
print(operator.contains((1, 2, 3, 4, 5), 9))

Output:

True
False
False
True
False

Python Identity Operators

The Python Identity Operators are used to compare the objects if both the objects are actually of the same data type and share the same memory location. There are different identity operators such as:

Identity Operator

Description

Syntax

is Operator

Returns True if both objects refers to same memory location, else returns False

obj1 is obj2

is not Operator

Returns False if both object refers to same memory location, else returns True

obj1 is not obj2

Python IS Operator

The is operator evaluates to True if the variables on either side of the operator point to the same object in the memory and false otherwise.

Example: In this code we take two integers, lists and strings. Then used the ‘is’ operator to check each datatype’s identity.

Python
# Python program to illustrate the use
# of 'is' identity operator
num1 = 5
num2 = 5

lst1 = [1, 2, 3]
lst2 = [1, 2, 3]
lst3 = lst1

str1 = "hello world"
str2 = "hello world"

# using 'is' identity operator on different datatypes
print(num1 is num2)
print(lst1 is lst2)
print(str1 is str2)
print(str1 is str2)

Output:

We can see here that even though both the lists, i.e., ‘lst1’ and ‘lst2’ have same data, the output is still False. This is because both the lists refers to different objects in the memory. Where as when we assign ‘lst3’ the value of ‘lst1’, it returns True. This is because we are directly giving the reference of ‘lst1’ to ‘lst3’.

True
False
True
True

Python IS NOT Operator

The is not operator evaluates True if both variables on the either side of the operator are not the same object in the memory location otherwise it evaluates False.

Example: In this code we take two integers, lists and strings. Then used the ‘is not’ operator to check each datatype’s identity.

Python
# Python program to illustrate the use
# of 'is' identity operator
num1 = 5
num2 = 5

lst1 = [1, 2, 3]
lst2 = [1, 2, 3]
lst3 = lst1

str1 = "hello world"
str2 = "hello world"

# using 'is not' identity operator on different datatypes
print(num1 is not num2)
print(lst1 is not lst2)
print(str1 is not str2)
print(str1 is not str2)

Output:

False
True
False
False

Difference between ‘==’ and ‘is’ Operator

While comparing objects in Pyhton, the users often gets confused between the Equality operator and Identity ‘is’ operator. The equality operator is used to compare the value of two variables, whereas the identities operator is used to compare the memory location of two variables. Let us see the difference with the help of an example.

Example: In this code we have two lists that contains same data. The we used the identity ‘is’ operator and equality ‘==’ operator to compare both the lists.

Python
# Python program to illustrate the use
# of 'is' and '==' operators
lst1 = [1, 2, 3]
lst2 = [1, 2, 3]

# using 'is' and '==' operators
print(lst1 is lst2)
print(lst1 == lst2)

Output:

False
True

You can read more about it here.



Previous Article
Next Article

Similar Reads

Python - tensorflow.identity()
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. identity() returns a Tensor with the same shape and contents as input. Syntax: tensorflow.identity(input, name) Parameters: input: It is a Tensor.name(optional): It defines the name for the operation. Returns: It returns
2 min read
numpy.identity() in Python
numpy.identity(n, dtype = None) : Return a identity matrix i.e. a square matrix with ones on the main diagonal. Parameters : n : [int] Dimension n x n of output array dtype : [optional, float(by Default)] Data type of returned array. Returns : identity array of dimension n x n, with its main diagonal set to one, and all other elements 0. Example: P
1 min read
numpy matrix operations | identity() function
numpy.matlib.identity() is another function for doing matrix operations in numpy. It returns a square identity matrix of given input size. Syntax : numpy.matlib.identity(n, dtype=None) Parameters : n : [int] Number of rows and columns in the output matrix. dtype : [optional] Desired output data-type. Return : n x n matrix with its main diagonal set
1 min read
Merging and Updating Dictionary Operators in Python 3.9
Python 3.9 is still in development and scheduled to be released in October this year. On Feb 26, alpha 4 versions have been released by the development team. One of the latest features in Python 3.9 is the merge and update operators. There are various ways in which Dictionaries can be merged by the use of various functions and constructors in Pytho
3 min read
Precedence and Associativity of Operators in Python
In Python, operators have different levels of precedence, which determine the order in which they are evaluated. When multiple operators are present in an expression, the ones with higher precedence are evaluated first. In the case of operators with the same precedence, their associativity comes into play, determining the order of evaluation. Opera
4 min read
Increment += and Decrement -= Assignment Operators in Python
If you're familiar with Python, you would have known Increment and Decrement operators ( both pre and post) are not allowed in it. Python is designed to be consistent and readable. One common error by a novice programmer in languages with ++ and -- operators are mixing up the differences (both in precedence and in return value) between pre and post
3 min read
Why Are There No ++ and -- Operators in Python?
Python does not include the ++ and -- operators that are common in languages like C, C++, and Java. This design choice aligns with Python's focus on simplicity, clarity, and reducing potential confusion. In this article, we will see why Python does not include these operators and how you can achieve similar functionality using Pythonic alternatives
3 min read
Python | Operators | Question 1
What is the output of the following code : C/C++ Code print 9//2 (A) 4.5 (B) 4.0 (C) 4 (D) Error Answer: (C)Explanation: The ‘//’ operator in Python returns the integer part of the floating number. Quiz of this QuestionPlease comment below if you find anything wrong in the above post
1 min read
Python | Operators | Question 2
Which function overloads the >> operator? (A) more() (B) gt() (C) ge() (D) None of the above Answer: (D) Explanation: rshift() overloads the >> operatorQuiz of this QuestionPlease comment below if you find anything wrong in the above post
1 min read
Python | Operators | Question 3
Which operator is overloaded by the or() function? (A) || (B) | (C) // (D) / Answer: (B) Explanation: or() function overloads the bitwise OR operatorQuiz of this QuestionPlease comment below if you find anything wrong in the above post
1 min read
Python | Operators | Question 4
What is the output of the following program : C/C++ Code i = 0 while i (A) 0 2 1 3 2 4 (B) 0 1 2 3 4 5 (C) Error (D) 1 0 2 4 3 5 Answer: (C)Explanation: There is no operator ++ in Python Quiz of this QuestionPlease comment below if you find anything wrong in the above post
1 min read
Python 3 - Logical Operators
Logical Operators are used to perform certain logical operations on values and variables. These are the special reserved keywords that carry out some logical computations. The value the operator operates on is known as Operand. In Python, they are used on conditional statements (either True or False), and as a result, they return boolean only (True
4 min read
How To Do Math in Python 3 with Operators?
Python3 provides us data types like integer and float along with various operators to perform mathematical calculations for graph plotting, machine learning algorithms, Statistical, data analytical purposes. An operator is a symbol that performs specific operations, which is very useful if one is frequently dealing with numbers. Operator precedence
5 min read
Augmented Assignment Operators in Python
An assignment operator is an operator that is used to assign some value to a variable. Like normally in Python, we write "a = 5" to assign value 5 to variable 'a'. Augmented assignment operators have a special role to play in Python programming. It basically combines the functioning of the arithmetic or bitwise operator with the assignment operator
4 min read
Inplace Operators in Python | Set 1 (iadd(), isub(), iconcat()...)
Python in its definition provides methods to perform inplace operations, i.e. doing assignments and computations in a single statement using an operator module. Example x += y is equivalent to x = operator.iadd(x, y) Inplace Operators in PythonBelow are some of the important Inplace operators in Python: iadd()isub()iconcat()imul()itruediv()imod()ia
3 min read
Inplace Operators in Python | Set 2 (ixor(), iand(), ipow(),…)
Inplace Operators in Python | Set 1(iadd(), isub(), iconcat()…) More functions are discussed in this articles. 1. ixor() :- This function is used to assign and xor the current value. This operation does "a^ = b" operation. Assigning is not performed in case of immutable containers, such as strings, numbers and tuples. 2. ipow() :- This function is
3 min read
Inplace vs Standard Operators in Python
Inplace Operators - Set 1, Set 2Normal operators do the simple assigning job. On other hand, Inplace operators behave similarly to normal operators except that they act in a different manner in case of mutable and Immutable targets. The _add_ method, does simple addition, takes two arguments, returns the sum, and stores it in another variable witho
3 min read
Chaining comparison operators in Python
Checking more than two conditions is very common in Programming Languages. Let's say we want to check the below condition: a < b < c The most common syntax to do it is as follows: if a < b and b < c : {...} In Python, there is a better way to write this using the Comparison operator Chaining. The chaining of operators can be written as
5 min read
Python Operators
In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators.  OPERATORS: These are the special symbols. Eg- + , * , /, etc.OPERAND: It is the value on which the operato
12 min read
Comparison Operators in Python
The Python operators can be used with various data types, including numbers, strings, booleans, and more. In Python, comparison operators are used to compare the values of two operands (elements being compared). When comparing strings, the comparison is based on the alphabetical order of their characters (lexicographic order).Be cautious when compa
5 min read
Python Bitwise Operators
Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic and logical computations. The value the operator operates on is known as the Operand.  Python Bitwise OperatorsPython bitwise operators are used to perform bitwise calculations on integers. The integers are first converted into
6 min read
Division Operators in Python
Division Operators allow you to divide two numbers and return a quotient, i.e., the first number or number at the left is divided by the second number or number at the right and returns the quotient. Division Operators in PythonThere are two types of division operators: Float divisionInteger division( Floor division)When an integer is divided, the
6 min read
Python Logical Operators
Python logical operators are used to combine conditional statements, allowing you to perform operations based on multiple conditions. These Python operators, alongside arithmetic operators, are special symbols used to carry out computations on values and variables. In this article, we will discuss logical operators in Python definition and also loo
6 min read
Python Arithmetic Operators
The Python operators are fundamental for performing mathematical calculations in programming languages like Python, Java, C++, and many others. Arithmetic operators are symbols used to perform mathematical operations on numerical values. In most programming languages, arithmetic operators include addition (+), subtraction (-), multiplication (*), d
5 min read
Assignment Operators in Python
The Python Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic, logical, and bitwise computations. The value the operator operates on is known as the Operand. Here, we will cover Different Assignment operators in Python. Operators Sign Description SyntaxAssignment Operator = Assi
11 min read
G-Fact 19 (Logical and Bitwise Not Operators on Boolean)
Most of the languages including C, C++, Java, and Python provide a boolean type that can be either set to False or True. In this article, we will see about logical and bitwise not operators on boolean. Logical Not (or !) Operator in PythonIn Python, the logical not operator is used to invert the truth value of a Boolean expression, returning True i
4 min read
Operators Precedence in Scala
An operator is a symbol that represents an operation to be performed with one or more operand. Operators are the foundation of any programming language. Which operator is performed first in an expression with more than one operators with different precedence is determined by operator precedence. For example, 10 + 20 * 30 is calculated as 10 + (20 *
3 min read
Boolean Operators - Django Template Tags
A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some limited features of a programming such as variable
5 min read
SQL Operators
SQL Operators perform arithmetic, comparison, and logical operations to manipulate and retrieve data from databases. In this article, we will discuss Operators in SQL with examples, and understand how they work in SQL. Operators in SQLOperators in SQL are symbols that help us to perform specific mathematical and logical computations on operands. An
5 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Article Tags :
Practice Tags :