Challenge - 5 Problems
Identity Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this pytest assertion?
Consider the following pytest test function. What will be the result of running this test?
PyTest
def test_identity(): a = [1, 2, 3] b = a assert a is b
Attempts:
2 left
💡 Hint
Remember that 'is' checks if two variables point to the same object in memory.
✗ Incorrect
Since 'b' is assigned to 'a', both variables point to the same list object. Therefore, 'a is b' is True and the assertion passes.
❓ Predict Output
intermediate2:00remaining
What happens when comparing two identical lists with 'is'?
What will be the result of this pytest test function?
PyTest
def test_identity_lists(): a = [1, 2, 3] b = [1, 2, 3] assert a is not b
Attempts:
2 left
💡 Hint
Two lists with the same content are different objects unless assigned explicitly.
✗ Incorrect
Although 'a' and 'b' have the same content, they are two separate list objects in memory. So 'a is not b' is True and the assertion passes.
❓ assertion
advanced2:00remaining
Which assertion correctly checks that two variables do NOT refer to the same object?
You want to write a pytest assertion to confirm that variables 'x' and 'y' are different objects. Which option is correct?
Attempts:
2 left
💡 Hint
Remember 'is not' checks identity, while '!=' checks value equality.
✗ Incorrect
'assert x is not y' checks that 'x' and 'y' are not the same object in memory, which is what is needed.
🔧 Debug
advanced2:00remaining
Why does this pytest assertion fail unexpectedly?
Given the code below, why does the assertion fail?
PyTest
def test_identity_failure(): a = 256 b = 256 assert a is b def test_identity_failure2(): x = 257 y = 257 assert x is y
Attempts:
2 left
💡 Hint
Python caches small integers from -5 to 256 for performance.
✗ Incorrect
Python reuses objects for small integers between -5 and 256, so 'a is b' is True for 256. For 257, new objects are created, so 'x is y' is False and assertion fails.
❓ framework
expert3:00remaining
How to write a pytest test that checks identity and reports a clear message on failure?
You want to write a pytest test that asserts two variables 'obj1' and 'obj2' are the same object. If they are not, the test should fail with the message: "Objects are not identical". Which code snippet achieves this?
Attempts:
2 left
💡 Hint
Use 'is' for identity and provide a message after the comma in assert.
✗ Incorrect
Using 'assert obj1 is obj2, "Objects are not identical"' checks identity and shows the message if the assertion fails.