pythonvariable-assignmentarray-indexing

Python Array variable assignment


I am newbie to python so having difficulty understand this code behavior for scenarios listed below.

I can understand the first 3 where the output is a=[1], b=[0] but in the last case why is the value of b getting changed to [1] ?

a = [0]
b = a[:]
a = [1]
print(a,b)

a = [0]
b = a[:]
a[0] = 1
print(a,b)

a = [0]
b = a
a = [1]
print(a,b)

a = [0]
b = a
a[0] = 1
print(a,b)

Solution

  • Here are some comments that should help clarify.

    a = [0]    # a is a new array
    b = a[:]   # b is a copy of a
    a = [1]    # a is a new array
    print(a,b) # [1] [0] because they are 2 different arrays
    
    a = [0]    # a is a new array
    b = a[:]   # b is a copy of a
    a[0] = 1   # modify a
    print(a,b) # [1] [0] because they are 2 different arrays
    
    a = [0]    # a is a new array
    b = a      # b is a reference to a (same array)
    a = [1]    # a is a new array, but b is still pointing to the first array
    print(a,b) # [1] [0] because they are 2 different arrays
    
    a = [0]    # a is a new array
    b = a      # b is a reference to a (same array)
    a[0] = 1   # modify a, which also modifies b since they are both references to the same array
    print(a,b) # [1] [1] because they are the same array
    

    You should check out this python visualizer to help clarify things, since it will show you exactly what object each reference is pointing to. Paste your code in there, then click Visualize Execution and step through the code to visualize the differences between these 4 blocks.

    Specifically in this case, pay close attention to what happens on the b = a lines. Both variables will point to the same underlying list.