Python Forum

Full Version: Sorting a copied list is also sorting the original list ?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, Big Grin
I would need your help to sort the copy of a list without modifying the initial list. Huh

for example, when I create a copy of the C1 list. Then I sort this copy. Both lists are unfortunately sorted. Undecided

def tri_ins(t):
    for k in range(1,len(t)):
        temp=t[k]
        j=k
        while j>0 and temp<t[j-1]:
            t[j]=t[j-1]
            j-=1
            t[j]=temp
    return t

C1=[7,3,6,5,4,2,1]
C2=C1
tri_ins(C2)
I know it's possible using the "sort" function but unfortunately I'm not allow to use it. Sad

C1=[7,3,6,5,4,2,1]
C2=C1
C2=sorted(C1)
Thank you for your help.
The problem is that you are not creating a copy. Lists are mutable, and as a consequence list variables are actually pointers to the lists rather than the lists themselves. So C2 = C1 just makes C2 point to the same list C1 points to. The easiest way to copy a list is with a full list slice (C2 = C1[:]. Note that this is a "shallow" copy. Any lists within the copied lists will still be references to their original list.
C1=[7,3,6,5,4,2,1]
C2=C1
This is just making C2 also point at the same object as C1

To make a new copy of the list use
c2 = c1[:]
or
c2 = list(c1)
oooooh ok... Dance
Thank you very much to both of you! Heart