Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
In Python programming, confusing value equality (==) with object identity (is) is one of the most common and dangerous sources of subtle bugs.
Python provides two specialized operator families to handle reference comparison and containment verification:
is, is not): Test whether two variables point to the exact same object at the exact same physical memory address.in, not in): Test whether a specific element exists inside a collection, sequence, or container (strings, lists, tuples, sets, dictionaries).+-------------------------------------------------------------------------+
| IDENTITY (is) vs EQUALITY (==) ANALOGY |
+-------------------------------------------------------------------------+
1. VALUE EQUALITY (==) -> Identical Twin Brothers:
- Ramesh and Suresh are identical twins wearing matching outfits.
- They have the same height, weight, and clothes.
- If you compare their appearance: ramesh == suresh -> TRUE!
- But they are two distinct living human beings!
- They have separate Aadhaar numbers and live in separate bodies:
ramesh is suresh -> FALSE!
2. OBJECT IDENTITY (is) -> Two Nicknames for One Legend:
- Amitabh Bachchan and "Big B".
- These are two different names pointing to the EXACT same person!
- amitabh is big_b -> TRUE! (id(amitabh) == id(big_b))
3. MEMBERSHIP (in / not in) -> Train Reservation Chart:
- You arrive at Hazrat Nizamuddin Station to board the Rajdhani Express.
- You scan the reservation chart pasted on the train door:
"Is 'Aarav Sharma' in passenger_list?" -> True or False!
+-------------------------------------------------------------------------+How data and code flow step-by-step
is and is notThe is operator evaluates to True if and only if id(x) == id(y). The is not operator evaluates to True if they point to different memory addresses:
None with isIn Python, None is a singleton—there is only ever one physical instance of None in the entire CPython process. According to the official PEP 8 style guide, you must always compare with None using is or is not, never with ==:
is for Numbers!A legendary trap in Python is that CPython pre-allocates an internal cache of all integers between -5 and 256 at startup:
is to check whether numbers or strings are equal! Always use == for values. Reserve is strictly for singletons like None, True, and False.in and not inThe in operator tests whether an item is found within a collection. The not in operator tests whether an item is absent:
== vs is| Feature | == (Value Equality) | is (Object Identity) |
|---|---|---|
| What It Checks | Checks if contents and values match | Checks if memory addresses (id()) match |
| Underlying Method | Calls __eq__() on the left object | Compares raw memory pointers in C |
| Use For Numbers | Yes (count == 10) | Never! (Breaks past 256) |
| Use For Strings | Yes (role == "ADMIN") | Never! (Subject to string interning) |
| Use For Singletons | Avoid (x == None is unpythonic) | Always! (x is None, x is not None) |
| Scenario | Anti-Pattern (Don't) | Best Practice (Do) | Why |
|---|---|---|---|
| Checking None | if status == None: | if status is None: | PEP 8 standard; immune to __eq__ tampering. |
| Comparing Numbers | if score is 100: | if score == 100: | is fails unexpectedly outside the small integer cache. |
| Dict Key Check | if key in dict.keys(): | if key in dict: | Checking dict directly performs $O(1)$ key lookup without creating views. |
| Negated Membership | if not item in items: | if item not in items: | not in is idiomatic, clean, and reads like plain English. |
+-------------------------------------------------------------------------+ | IDENTITY & MEMBERSHIP OPERATORS CHEAT SHEET | +-------------------------------------------------------------------------+ - == (Equal): Compares contents/values: [1, 2] == [1, 2] is True - is (Identity): Compares memory addresses: [1, 2] is [1, 2] is False! - Singletons: Always write 'if x is None:' or 'if x is not None:' - Small Int Cache: CPython caches -5 to 256; NEVER use 'is' on numbers! - in (Membership): Tests containment in str, list, tuple, set, dict - not in: Tests absence: 'admin' not in blacklisted_users - Dict 'in': Checks keys by default! Use dict.values() for values +-------------------------------------------------------------------------+
=) with Equality (==)A single equals sign = assigns a value. Two equals signs == checks for equality:
and / orBeginners often write if x == 1 or 2:, which always evaluates to True because non-zero integers are truthy!
[1, 2] == [1, 2] vs [1, 2] is [1, 2]?A. True and True B. True and False C. False and True D. False and False
result is None?A. if result == None: B. if result is None: C. if result.equals(None): D. if None in result:
'admin' in {'admin': True, 'guest': False} test by default?A. Whether 'admin' is a value in the dictionary B. Whether 'admin' is a key in the dictionary C. Both keys and values D. Raises a TypeError
x = 1000; y = 1000; x is y evaluate to False, while x = 10; y = 10; x is y evaluates to True?A. Python has a bug with numbers containing zeros B. CPython pre-allocates and caches small integers from -5 to 256 as shared objects, but allocates new objects for larger numbers C. Numbers above 500 automatically convert to floats D. is can only compare single-digit numbers
tag is NOT inside allowed_tags?A. if not (tag in allowed_tags): B. if tag not in allowed_tags: C. if (tag in allowed_tags) == False: D. if tag in allowed_tags is False:
Write a complete, runnable Python script that models a Role-Based Access Control (RBAC) security gateway for a cloud infrastructure portal. Use is and is not to validate database connection singletons, and use in and not in to verify IP allowlists and user permission privileges.
How data and code flow step-by-step
In the next lesson, we will continue your Python learning journey with Bitwise Operators (6: Operators).
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Logical Operators | Bitwise Operators |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.