AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Easypythonidentity

~60s

Equality against identity

What does this Python program print?

a = [1, 2]
b = [1, 2]
print(a == b, a is b)
Show the answer and the worked solution

Correct answer: B.

True False

Worked solution

  1. a and b hold the same elements, so a == b compares contents and is True.
  2. Each list display builds a fresh list object, so a and b are different objects and a is b is False.
  3. 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.

Equality against identity — Aptitude Question

Equality against identity: What does this Python program print? Answer and worked solution on CodeKairo.

Question

What does this Python program print?

a = [1, 2]
b = [1, 2]
print(a == b, a is b)

Options

  1. True True
  2. True False
  3. False True
  4. False False
Show the answer and the worked solution

Correct answer: B. True False

Worked solution

  1. a and b hold the same elements, so a == b compares contents and is True.
  2. Each list display builds a fresh list object, so a and b are different objects and a is b is False.
  3. 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