Python Forum
Why is my original list also sorted?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why is my original list also sorted?
#1
I have a simple list of words and a function to sort those words.

def sortAlpha(words):        
        words.sort()        
        return words;
I get the words:

def gettheWords():        
        textFile = pathToText + 'words'
        textFileBody = open(textFile, 'r')
        words = textFileBody.readlines()
        textFileBody.close() 
        return words;

theWords = gettheWords()
Then I do:

sortedWords = sortAlpha(theWords)
But when I look at my original list: theWords, that list is also sorted alphabetically. Why is that??

It seems Python does not make a new list, just uses the new name as an alias for the original?

Is there some way to change this behaviour?
Reply
#2
words.sort() sorts the list in place
sortedwords = sorted(words) will return a new sorted list
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Failing to print sorted files tester_V 4 1,188 Nov-12-2022, 06:49 PM
Last Post: tester_V
  set and sorted, not working how expected! wtr 2 1,254 Jan-07-2022, 04:53 PM
Last Post: bowlofred
  Looping through nested elements and updating the original list Alex_James 3 2,069 Aug-19-2021, 12:05 PM
Last Post: Alex_James
  Why changing data in a copied list changes the original list? plumberpy 3 2,189 Aug-14-2021, 02:26 AM
Last Post: plumberpy
  HELP! i need the solution to show for original indexing bntayfur 1 1,487 Oct-02-2020, 06:44 PM
Last Post: buran
  How to make elements return sorted? notsoexperienced 4 3,164 Sep-24-2020, 09:00 AM
Last Post: perfringo
  get original code after being encoded to UTF-8 ashok 18 5,752 Sep-08-2020, 04:17 AM
Last Post: ndc85430
  Outputting Sorted Text files Help charlieroberrts 1 1,684 Jul-05-2020, 08:37 PM
Last Post: menator01
  Creating new list based on exact regex match in original list interjectdirector 1 2,252 Mar-08-2020, 09:30 PM
Last Post: deanhystad
  sorted function example mystery sabaidii2 4 2,480 Feb-10-2020, 09:37 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

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