Question 23: Understanding Integer Caching in Python

This question tests your understanding of Python’s integer caching mechanism.

Question 23: Understanding Integer Caching in Python

Question: Integer Caching

What will be the output of the code below?

a = 256
b = 256
print(a is b)

a = 257
b = 257
print(a is b)
















Answer: B

Explanation:

In Python, small integer objects in the range -5 to 256 are preallocated in memory for performance reasons.

When a and b are both set to 256, they reference the same memory location, so a is b returns True.

For integers outside this range, such as 257, separate memory locations are allocated, so a is b returns False when a and b are both set to 257.

Leave a Reply