Вопрос

I have a Python code, where I first define two lists, then I make them identical and do the same operation on them after they are identical - but the result is not the same:

test1 = [[[0],[0]]]*2
test2 = [[0]]*2

test2[0] = [[0],[0]]
test2[1] = [[0],[0]]

print 'They are identical?:',test1 == test2 # gives True

# Now that test1 == test2 do the same operation on test list 1 and 2:

test1[0][0] = 2
test2[0][0] = 2

print test1
print test2

This gives

[[2, [0]], [2, [0]]]   # test1
[[2, [0]], [[0], [0]]] # test2

Can somebody explain the difference to me?

Это было полезно?

Решение

If x is a list,

x * 2

Returns two times the same elements from the list.

As lists are passed by references, this means:

>>> A = 2 * [[0]]
>>> B = [[0], [0]]

Will actually not have the same structure: both A[0] and A[1] point to the same list, while B[0] and B[1] point to two different lists.

And indeed, if you try:

>>> A[0] == A[1]
True
>>> A[0] is A[1]
True
>>> A[0].append(1)
>>> A
[[0, 1], [0, 1]]

While:

>>> B[0] == B[1]
True
>>> B[0] is B[1]
False
>>> B[0].append(1)
>>> B
[[0, 1], [0]]

Другие советы

this command

test1 = [[[0],[0]]]*2

is equivalent of this 2:

a = [[0], [0]]
test1 = [a, a]

and then you assigning value to test1[0][0], you are changing value of a list. Of course test[1] changes to, because it is same a list

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top