Python Forum
Sorting a copied list is also sorting the original list ? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Sorting a copied list is also sorting the original list ? (/thread-17455.html)



Sorting a copied list is also sorting the original list ? - SN_YAZER - Apr-11-2019

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.


RE: Sort list - ichabod801 - Apr-11-2019

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.


RE: Sort list - Yoriz - Apr-11-2019

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)



RE: Sorting a copied list is also sorting the original list ? - SN_YAZER - Apr-11-2019

oooooh ok... Dance
Thank you very much to both of you! Heart