Это хороший вопрос. Давайте разберемся, что происходит.
Один из инструментов, который у вас есть, когда вы получаете подобные вопросы, - это встроенная функция id
. id
- это способ проверить, действительно ли объект совпадает с предыдущим или нет.
Давайте использовать id
в вашем коде.
def foo(l):
print("The ID of r in the function foo is {}".format(id(r)))
print("The ID of l in the function foo is {}".format(id(l)))
r.append(l)
print("The ID of r in the function foo after the append is {}".format(id(r)))
print("The ID of the the items in r: {}, after first append".format(id(r[0])))
l[0], l[1] = l[1], l[0]
print("The ID of l in the function foo after the swap is {}".format(id(l)))
r.append(l)
print("The ID of r in the function foo after second append is {}".format(id(r)))
print("The ID of the the items in r: {}, {} after second append".format(id(r[0]), id(r[1])))
r = []
print("The ID of r in the beginning is {}".format(id(r)))
l = [0, 1]
print("The ID of l in the beginning is {}".format(id(l)))
print(l)
foo(l)
print(l)
print("The ID of l after the foo call is {}".format(id(l)))
print(r)
print("The ID of r after the foo call is {}".format(id(r)))
print("The ID of the the items in r: {}, {}".format(id(r[0]), id(r[1])))
Мой результат (ваш будет отличаться):
The ID of r in the beginning is 4374077736
The ID of l in the beginning is 4374122152
[0, 1]
The ID of r in the function foo is 4374077736
The ID of l in the function foo is 4374122152
The ID of r in the function foo after the append is 4374077736
The ID of the the items in r: 4374122152, after first append
The ID of l in the function foo after the swap is 4374122152
The ID of r in the function foo after second append is 4374077736
The ID of the the items in r: 4374122152, 4374122152 after second append
[1, 0]
The ID of l after the foo call is 4374122152
[[1, 0], [1, 0]]
The ID of r after the foo call is 4374077736
The ID of the the items in r: 4374122152, 4374122152
Это говорит нам о том, что здесь всегда есть только две переменные.
Даже внутри r
. Вы добавляете один и тот же объект дважды. И этот объект также может быть изменен извне.
Таким образом, всякий раз, когда он изменяется, он также изменяется в вашем содержащем списке .
Каждый элемент в r
указывает на то же l
.