Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

⭐ Python Special Operators: Identity & Membership

Python Special Operators - Identity and Membership

Special operators help you check identity and membership — essential tools for working with objects and collections.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
📑 On this page:
  • What are Special Operators?
  • Identity Operators (is, is not)
  • The 'is' Operator
  • The 'is not' Operator
  • Membership Operators (in, not in)
  • The 'in' Operator
  • The 'not in' Operator
  • Identity vs Equality
  • Real-World Applications
  • Common Mistakes
  • Try It Yourself
  • Quick Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
📚 What You'll Learn Here
  • What special operators are — identity and membership operators in Python
  • Identity operators — using is and is not to compare object identity
  • Membership operators — using in and not in to check for membership
  • Identity vs Equality — understanding the difference between is and ==
  • Real-world applications — checking None, finding items in collections
  • Common mistakes — and how to avoid them

What are Special Operators?

Python has two types of special operators that don't fit neatly into the arithmetic, comparison, or logical categories. They are Identity Operators and Membership Operators. These operators are used for specific purposes — checking if two objects are the same, or checking if a value exists in a collection.

💡 Key insight: While they might seem simple, these operators are used constantly in real-world Python code. They're essential for working with objects, lists, dictionaries, and checking for None.

Let's explore each of these operators in detail with practical examples.

1. Identity Operators (is, is not)

Identity operators compare the memory location of two objects. They check if two variables refer to the same object in memory, not just if they have the same value.

Think of it like two people pointing to the same physical chair. Even if the chairs look identical, if they're pointing to different chairs, they're not the same. is checks if they're pointing to the exact same chair.

The 'is' Operator

The is operator returns True if two variables point to the same object in memory.

# The 'is' Operator
a = [1, 2, 3]
b = a  # b points to the same object as a
c = [1, 2, 3]  # c is a new object with the same values

print(a is b)   # Output: True (same object)
print(a is c)   # Output: False (different objects)
print(a == c)   # Output: True (same values)

# With integers (small integers are cached)
x = 10
y = 10
print(x is y)   # Output: True (Python caches small integers)

# With strings (interned)
s1 = "hello"
s2 = "hello"
print(s1 is s2)  # Output: True (strings are interned)

# With None
value = None
print(value is None)  # Output: True

📖 Important: Python caches small integers (-5 to 256) and some strings for performance. This is why 10 is 10 returns True. But you should never rely on this behavior — always use == for value comparison.

The 'is not' Operator

The is not operator returns True if two variables point to different objects in memory.

# The 'is not' Operator
a = [1, 2, 3]
b = a
c = [1, 2, 3]

print(a is not b)   # Output: False (same object)
print(a is not c)   # Output: True (different objects)

# Common use: checking if a value is not None
value = "Hello"
if value is not None:
    print("Value exists!")  # This runs

# Another example
x = None
if x is not None:
    print("x has a value")
else:
    print("x is None")  # This runs

2. Membership Operators (in, not in)

Membership operators check if a value exists in a sequence (like a list, tuple, string, or dictionary). They are used to test whether an element is part of a collection.

Think of it like searching for a specific book in a library. You're not looking at the books themselves — you're just checking if a particular book is present in the library's collection.

The 'in' Operator

The in operator returns True if the value is found in the sequence.

# The 'in' Operator with Lists
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits)   # Output: True
print("grape" in fruits)   # Output: False

# With Strings
text = "Python Programming"
print("Python" in text)    # Output: True
print("Java" in text)      # Output: False

# With Dictionaries (checks keys)
person = {"name": "Alice", "age": 25}
print("name" in person)    # Output: True
print("address" in person) # Output: False

# With Tuples
numbers = (1, 2, 3, 4, 5)
print(3 in numbers)        # Output: True
print(10 in numbers)       # Output: False

The 'not in' Operator

The not in operator returns True if the value is not found in the sequence.

# The 'not in' Operator
fruits = ["apple", "banana", "cherry"]
print("grape" not in fruits)   # Output: True
print("apple" not in fruits)   # Output: False

# With Strings
text = "Hello World"
print("Java" not in text)      # Output: True
print("Hello" not in text)     # Output: False

# With Dictionaries (checks keys)
person = {"name": "Alice", "age": 25}
print("address" not in person) # Output: True
print("name" not in person)    # Output: False

# User authentication check
blocked_users = ["hacker", "spammer"]
username = "alice"
if username not in blocked_users:
    print("User is allowed")
else:
    print("User is blocked")

3. Identity vs Equality

One of the most common confusions in Python is the difference between is and ==.

Operator Checks Example When to Use
== Value equality a == b When you want to check if values are the same
is Object identity (memory location) a is b When you want to check if they're the same object
# == vs is
a = [1, 2, 3]
b = [1, 2, 3]  # Same values, different object

print(a == b)   # Output: True (values are equal)
print(a is b)   # Output: False (different objects)

# With None (always use 'is')
x = None
print(x is None)    # Output: True (correct)
print(x == None)    # Output: True (works but not recommended)

# With singletons
print(True is True)    # Output: True
print(False is False)  # Output: True

# Best practice: Use 'is' for None, True, False
# Use '==' for everything else

⚠️ Best Practice: Always use is when checking for None, True, or False. Use == for everything else.

4. Real-World Applications

✅ Checking for None

# Database query example
result = get_user_from_database(user_id)

if result is None:
    print("User not found")
else:
    print(f"User found: {result.name}")

🔍 Finding Items in Collections

# Shopping cart check
cart = ["laptop", "mouse", "keyboard"]
if "laptop" in cart:
    print("Laptop is in your cart")

# User authentication
blocked_users = ["hacker", "spammer"]
if username not in blocked_users:
    print("User is allowed to login")

🔄 Singleton Pattern Check

# Singleton pattern
class DatabaseConnection:
    _instance = None
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

# Both objects are the same instance
db1 = DatabaseConnection()
db2 = DatabaseConnection()
print(db1 is db2)  # Output: True

5. Common Mistakes to Avoid

❌ Mistake 1: Using == instead of is for None

# WRONG (works but not recommended)
if value == None:
    print("Value is None")

# CORRECT
if value is None:
    print("Value is None")

❌ Mistake 2: Using is for value comparison

# WRONG (unreliable)
a = 1000
b = 1000
if a is b:  # This might be False (depending on Python optimization)
    print("Equal")

# CORRECT
if a == b:
    print("Equal")

❌ Mistake 3: Using in on dictionaries incorrectly

# WRONG (checks keys only, not values)
person = {"name": "Alice", "age": 25}
if "Alice" in person:  # This is False!
    print("Found Alice")

# CORRECT (check values)
if "Alice" in person.values():
    print("Found Alice")

# CORRECT (check keys)
if "name" in person:
    print("Name key exists")

Try It Yourself!

Experiment with special operators directly in your browser. Modify the code and see the results in real time.

Loading Pyodide... 0%
Python Code Editor
========================================
SPECIAL OPERATORS
========================================

1. IDENTITY OPERATORS (is, is not)
a is b: True (same object)
a is c: False (different objects)
a == c: True (same values)

2. MEMBERSHIP OPERATORS (in, not in)
'apple' in fruits: True
'grape' in fruits: False

3. IDENTITY vs EQUALITY
x == y: True (values are equal)
x is y: False (different objects)

4. CHECKING None
value is None: True

✅ Special operators are essential for identity and membership checks!
🏆

🎉 You've Mastered Python Special Operators!

You understand identity operators (is, is not) and membership operators (in, not in). These are essential for working with objects and collections in Python!

Quick Quiz – Test Your Knowledge

1. What does is check in Python?
2. Which operator checks if a value exists in a sequence?
3. How should you check if a variable is None?
4. What is the result of [1, 2, 3] is [1, 2, 3]?
5. What does in check for dictionaries?

Frequently Asked Questions

🤔 What's the difference between is and ==? ▼

is checks if two variables point to the same object in memory (identity). == checks if the values are equal. Use is for None, True, False; use == for everything else.

🔧 Does in work with dictionaries? ▼

Yes! in checks for keys in dictionaries. To check values, use in my_dict.values(). To check key-value pairs, use in my_dict.items().

📐 What is object identity? ▼

Every object in Python has a unique memory address. Object identity means the object's location in memory. You can check an object's ID using id(). is compares these IDs.

⚡ Are is and == ever the same? ▼

They can be the same for small integers (-5 to 256) and interned strings, because Python caches these objects. However, you should never rely on this behavior. Always use the appropriate operator for your purpose.

📊 Can I use in with strings? ▼

Yes! in checks if a substring exists in a string. For example, "Python" in "Python Programming" returns True.

🎯 When should I use is not vs !=? ▼

Use is not for identity checks (like x is not None) and != for value inequality checks. They serve different purposes and are not interchangeable.

📚 Where to Go From Here

Now that you understand Python special operators, here are some related topics to explore:

📝 Operators Assignments

Practice what you've learned

🎯 Decision Making

Use conditions to control program flow

📚 Functions

Learn about functions in Python

📖 Related Tutorials
  • Logical Operators
  • Relational Operators
  • Bitwise Operators
  • Arithmetic Operators
📖 Interview & FAQ Resources
  • SQL - Displaying Data from Multiple Tables FAQ
  • SQL Window Functions & Analytic Functions FAQ
  • Python Data Types Interview Questions
  • Python Tuples and Sets Interview Questions
  • Java Basic Input/Output Interview Questions
  • Java Advanced Threads and Concurrency Interview Questions
Previous: Bitwise Operators Next: Operators Assignments →