In the last lesson, we introduced the concept of references and mentioned that everything is always passed by reference in Python. Let us experiment with a list as our first known mutable object.
But first, we need to learn about tools for our experiments: the id
function and the is
operator.
The id
and is
methods
If you refer to the function description (help(id)
), the documentation will tell you:
id(obj, /)
Return the identity of an object.
It is guaranteed to be unique among simultaneously existing objects.
The id
function returns a unique identifier of an object passed to it as an argument and by reference.
The identifier is an ordinary number. But each object has a unique identifier.
It means that any two objects will always have different identifiers. Python does not preserve identifiers from one run to the next, so the object-identifier relationship is unbreakable within one run.
That is why identifiers help keep track of object references we pass between different code sections.
The object identifier will be the same regardless of what reference we use to access the object:
a = "some string"
b = a
id(a) # 139739990935280
id(b) # 139739990935280
print(a is b) # => True
When we assign a value of one variable to another, we create a new named reference to the original value. Therefore id(a)
and id(b)
return the same result.
The is
operator checks if the identifiers of its operands are equal. In this example, both variables refer to the same object, so checking a is b
gives True
.
Checking for equality of identifiers is very quick. And it is convenient to use when we deal with so-called single objects.
The most famous Python singles are:
True
False
None