Interview question
What is the difference between == and is in Python? Python में == और is में क्या अंतर है?
Answer
| Operator | Checks |
|---|---|
| == | Value equality - do the objects contain the same value? |
| is | Identity equality - are they the SAME object in memory? |
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # True - same values
print(a is b) # False - different objects in memory
print(a is c) # True - c points to the SAME object as a
# Small integer caching - CPython caches small ints (-5 to 256)
x = 100
y = 100
print(x is y) # True - both point to the same cached int object
x = 1000
y = 1000
print(x is y) # False (usually) - large ints not cached, separate objects
# Best practice: use 'is' only for None, True, False comparisons
if a is None:
print('a is None')| Operator | क्या check करता है |
|---|---|
| == | Value equality - same values हैं? |
| is | Identity equality - memory में same object हैं? |
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # True - same values
print(a is b) # False - अलग objects
print(a is c) # True - same object
# Small integer caching
x = 100
y = 100
print(x is y) # True - cached
# Best practice: 'is' सिर्फ None, True, False के लिए
if a is None:
print('a is None')Was this answer clear?