14/15 Odd/unexpected variable assignment behaviour


#1

Just looking at line 3,4 and 5 in my code below:-

def remove_duplicates(lst):
    i = 0
    # result = []
    # result += lst
    result = lst
    while i < (len(result)-1):
        n = i + 1
        while n < len(result):
            if result[i] == result[n]:
                del(result[n])
            else:
                n += 1
        i += 1
    print lst
    print result
    return result
    
remove_duplicates([4,5,5,4])

When I run the code as is, the two printed lists are [4,5] and [4,5] respectively, that is, altering my 'copy' of the passed parameter, is altering the parameter too!! If I comment line 5 out and uncomment 3,4 it works fine. Can anyone explain this behaviour??

Cheers.


#2

Hi @dickiewilly,

Whenever you do:

list1 = list2

then list1 holds a reference to the original list2. So, any changes to list1 get referenced to list2 and thus reflect in both of them. You need to use the list method to generate a copy of list2 and then assign a reference to that new copy to list1:

list1 = list(list2)

This property of lists is called mutation, and as you would have guessed, doesn't occur with ints or floats.

Hope it helps! :smiley: