Bird
0
0

What will be the outcome of this pytest assertion?

medium📝 Predict Output Q5 of 15
PyTest - Writing Assertions
What will be the outcome of this pytest assertion?
str1 = 'hello'
str2 = ''.join(['h', 'e', 'l', 'l', 'o'])
assert str1 is str2
AThe assertion will pass because both strings have the same content
BThe assertion will fail because str1 and str2 are different objects
CThe assertion will fail because str2 is None
DThe assertion will pass because Python interns all strings automatically
Step-by-Step Solution
Solution:
  1. Step 1: Understand string interning

    Python may intern some strings, but dynamically created strings like str2 are usually new objects.
  2. Step 2: Check identity vs equality

    is checks object identity, not content equality.
  3. Step 3: Analyze the assertion

    str1 and str2 have same content but are different objects, so assert str1 is str2 fails.
  4. Final Answer:

    The assertion will fail because str1 and str2 are different objects -> Option B
  5. Quick Check:

    Same content ≠ same object [OK]
Quick Trick: Use 'is' for identity, not string content equality [OK]
Common Mistakes:
MISTAKES
  • Assuming strings with same content are always same object
  • Confusing 'is' with '==' for strings

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PyTest Quizzes