Multiple variables referring to the same object
The following example demonstrates that multiple variables can refer to the same object.
This is demonstrated with this simple script:
L1 = []
L1.append(2)
L1.append(3)
L2 = L1
L2.append(5)
L2.append(7)
for p in L1:
print(p)
if (id(L1) != id(L2)):
print('id differs')
if (L1 is L2):
print('L1 is the same object as L2')
The assignment of
L1
to
L2
does not copy the object but creates another name for the same object. Thus, when
5
and
7
are appended to the underlying object via
L2
, the newly appended numbers can be seen by
iterating over
L1
, which prints the four numbers
2
,
3
,
5
and
7
.
The built-in function
id()
returns a number that corresponds to an object's identity. If
id(x)
and
id(y)
return the same number, both
x
and
y
refer to the same object.
Python has the special
operator is
that returns
True
if the object on its left side is the same object on its right side.
Global/local variables in a function
A variable that is only referenced in a
function, but not assigned to, is implicitly a global variable.
In order to make explicitly mark a variable in a function as global, the
global
statement must be used.
The underscore variable
It's possible to use just an underscore (_
) as a variable name:
a = 'foo'
b = 'bar'
_ = 'baz'
print(f'{a} {b} {_}')
Usually, assigning a value to the underscore variable indicates that the programmer is not inending to use that variable later, for example when
unpacking an iterable:
X = ( 42, 'hello world' )
#
# We're only interested in the number that answers
# everything, but not the associated text:
#
num, _ = X
print(num)
#
# 42