Search code examples
pythondeep-copy

Python list sorting and indexing


I am having issue understanding and solving the following issue with lists, sorting and indexing. Here is the code example:

import random as rdm
a=[]
for i in range(3):
    a.append([i,rdm.randint(-5,5)])
print a
b = sorted(a,key=lambda a:a[1])
print b
c = []
for j in range(len(b)):
    c.append(b[j])
print c
c[0][1] = 0
print a
print b
print c

Notice how changing one value of "C" changed "b" and "a". How can I prevent it from happening? In other words. I do not want the values of "a" changed doesn't matter what happens to "b" or "c"


Solution

  • In your code, when you write:

    c.append(b[j])
    

    You are adding into c a reference to the object b[j].

    If you want b and c to be independent of a, you must do a deep copy of the objects.

    import copy
    b = sorted (copy.deepcopy(a), lambda a : a[1])