Search code examples
pythonobjectbubble-sort

assigned in python considered as a copy of an object


I don't understand the reason that in the first example, b is considered as a copy of a and it will change with a but not in the second example

def bubbleSort(alist):
    for passnum in range(len(alist)-1,0,-1):
        for i in range(passnum):
            if alist[i]>alist[i+1]:
                temp = alist[i]
                alist[i] = alist[i+1]
                alist[i+1] = temp
    return  alist

a=[3,2,1]
b=a
a=bubbleSort(a)
print(a)
print(b)

The output:

[1, 2, 3]
[1, 2, 3]

a=[3,2,1]
b=a
a=[1,2,3]

print(a)
print(b)

Output:

[1, 2, 3]
[3, 2, 1]

Solution

  • a=[3,2,1]
    b=a # **here you're refrencing by memory not value**
    a=bubbleSort(a)
    
    print id(a) 
    print id(b)
    
    # these both will give you same memory reference
    
    print(a)
    print(b)
    

    In the second example when you're doing b=a you're referencing by memory, but when you did a=[1,2,3] you're associating a to a new memory reference b is still bound to the old one.

    a = [3,2,1]
    b=a
    
    print id(b) #4376879184
    print id(a) #4376879184
    
    
    #they will be having the same id
    
    a = [1,2,3]
    #now you have assigned a new address which will have the new array
    
    print id(b) #4376879184
    print id(a) #4377341464
    #they will be having different id now