Python Forum
Sorting a copied list is also sorting the original list ?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sorting a copied list is also sorting the original list ?
#1
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.
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
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)
Reply
#4
oooooh ok... Dance
Thank you very much to both of you! Heart
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  HELP!!! string logical sorting kucingkembar 13 891 Aug-09-2024, 07:17 PM
Last Post: snippsat
  Strange behavior list of list mmhmjanssen 3 901 May-09-2024, 11:32 AM
Last Post: mmhmjanssen
Thumbs Up Sorting Steps MoreMoney 19 2,265 Mar-31-2024, 10:59 AM
Last Post: Pedroski55
  No matter what I do I get back "List indices must be integers or slices, not list" Radical 4 1,899 Sep-24-2023, 05:03 AM
Last Post: deanhystad
  Variable sorting methods for Enum DataClasses koen 1 1,132 May-30-2023, 07:31 PM
Last Post: deanhystad
  Delete strings from a list to create a new only number list Dvdscot 8 2,341 May-01-2023, 09:06 PM
Last Post: deanhystad
  Need help with sorting lists as a beginner Realist1c 1 1,041 Apr-25-2023, 04:32 AM
Last Post: deanhystad
  List all possibilities of a nested-list by flattened lists sparkt 1 1,348 Feb-23-2023, 02:21 PM
Last Post: sparkt
  Check DataFrames with different sorting in columns and rows Foxyskippy 0 978 Nov-19-2022, 07:49 AM
Last Post: Foxyskippy
  Сheck if an element from a list is in another list that contains a namedtuple elnk 8 2,563 Oct-26-2022, 04:03 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020