pythonedx

Why is the last statement false? (edx)


a = [1,2,3] 

b = a
a == b
True
a is b
True 

b = a[:]
a == b
True
a is b
False

Why is the last statement false? "b = a[:]" What is the difference of the line from the other line?


Solution

  • a[:] makes a shallow copy of a meaning that b is a new list and is not the same as a (but the inner elements if a was a 2d list would be the same)

    If you did:

    a = [[1],[2],[3]]
    b = a[:]
    b is a
    >>> False
    b[0] is a[0] 
    >>> True