Only by complementing the reply by @Woss...
Sequence multiplication
In the sequence documentation, the description of the operator of addition and multiplication between sequences and integers defines the following:
-- Free translation of parts relevant to the problem --
Being s
and t
sequences of the same type and n
an integer
s + t
: the concatenation of s
and t
.
Example:
[0, 1, 2] + [3, 4, 5]
# [0, 1, 2, 3, 4, 5]
s * n
or n * s
: equivalent to add s
with himself n
times.
Observing: The items in the sequence s
are not copied, but referenced multiple times. [Note 2 to the documentation]
Example:
[0] * 3
# [0, 0, 0]
# Mesmo que
[0] + [0] + [0]
# [0, 0, 0]
If you look at note 2 in the documentation it is specified that the items of the multiplied sequences are not copied, but referenced (at least the mutable types, as already explained in the @Woss response and in python documentation).
So:
s = [[]] * 3
It would be the same as creating an empty list and referencing it n
times on the external list:
_tmp = []
s = [_tmp, _tmp, _tmp]
print(s)
# [[], [], []]
Consequently _tmp
will reflect on all elements of s
since they all reference the same list:
s[0].append(1)
print(s)
# [[1], [1], [1]]
_tmp.append(2)
print(x)
# [[1, 2], [1, 2], [1, 2]]
Implementing id() in Cpython
In the job documentation id()
explains that the function returns the "identity" of an object, where it is an integer and is guaranteed to be unique during the lifetime of that object.
Finally there’s a note saying:
Cpython implementation Detail: This is the address of the Object in memory.
That in free translation would be:
Cpython implementation detail: This is the address of the object in memory.
I mean, that’s why we use the function id()
, because it is guaranteed that if the memory address is the same, the variables reference the same object.
Example:
lista = []
print(id(lista))
# 139942416872384
ref = lista
print(id(ref))
# 139942416872384
outra_lista = []
print(id(outra_lista))
# 139942416112048
Notice that lista
and ref
point to the same memory address, and so possess their id
equal, already outra_lista
is another object in memory. Remembering that the numbers above vary with each run of the program, I used only for example.
Perfect! Thank you.
– Matheus Lima