Search code examples
pythonlistinitializationequality

Why does an operation on two identical lists end up in different results?


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?


Solution

  • 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]]