Python Forum

Full Version: Why is my original list also sorted?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
words.sort() sorts the list in place
sortedwords = sorted(words) will return a new sorted list