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
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.
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(b) return the same result.
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
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: