Remember
id() identifies an object during its lifetime. Identity compares objects; it is different from comparing their values.
id() identifies an object during its lifetime. Identity compares objects; it is different from comparing their values.
Follow the example, change its sample, and compare what happens.
Explain the result and test your understanding.
Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.
Follow the code and watch its state change. Guided simulation.
items = [3]
other = items
print(id(items) == id(other))Top-level scope
[3]id() identifies an object during its lifetime. Identity compares objects; it is different from comparing their values.
(no output)
What do you expect this program to print?
EXAMPLE INSTRUCTIONS
items = [3]
other = items
print(id(items) == id(other))
|
v
DISPLAYED RESULT
True
FINAL BINDINGS
items --> object 1 (list)
other --> object 1 (list)
object 1: [3]Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.
Choose a sample and follow its execution. Guided simulation.
items = [3]
other = items
print(id(items) == id(other))Top-level scope
[3]The example has finished. Compare the final output with the values and references above.
True
What do you expect this program to print?
items = [3]
other = items
print(id(items) == id(other))id() FunctionThe id() function in Python returns a unique identifier for a given object. This identifier is the object's memory address, which remains constant during the object's lifetime.
id(object)
object – Any Python object (string, list, number, etc.)x = 10
print(id(x))
140709661559888
(Output will vary depending on your system)
a = 100
b = 100
print(id(a) == id(b))
True
In CPython, small integers and strings are cached, so variables with the same value may share the same ID.
x = [1, 2, 3]
y = [1, 2, 3]
print(id(x) == id(y))
False
x and y are different list objects, even though they have the same content.
is)In Python interviews, id() is often discussed in the context of is vs == comparisons, especially for mutable vs immutable types.
id(object) returns the unique identity (memory address) of the object.is keyword.Create two variables with the same value. Check if their IDs are equal. Then change one value and compare again.
a = "hello"
b = "hello"
print("Before change:", id(a) == id(b))
b = b + "!"
print("After change:", id(a) == id(b))
Connect what you noticed in the example with the idea below.
id() identifies an object during its lifetime. Identity compares objects; it is different from comparing their values.
id() is a stable identifier across all Python runs.
This is the misconception to avoid.Reference checks are optional and do not count toward course progress.