Equality against identity — Aptitude Question
Equality against identity: What does this Python program print? Answer and worked solution on CodeKairo.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Easy
- Time target: 60 seconds
Question
What does this Python program print?
a = [1, 2]
b = [1, 2]
print(a == b, a is b)Options
- True True
- True False
- False True
- False False
Show the answer and the worked solution
Correct answer: B. True False
Worked solution
- a and b hold the same elements, so a == b compares contents and is True.
- Each list display builds a fresh list object, so a and b are different objects and a is b is False.
- The line therefore prints True False.
Answer: True False.
The idea
is compares identity and == compares value. Reaching for is on anything other than None, True or False is almost always a mistake.
Shortcut. Two list displays always build two objects, so is must be False; the same contents make == True.
Common trap. "True True" assumes equal small lists are cached like small integers; lists are mutable and never shared this way.
All Programming Fundamentals questions · placement mock tests