Skip to main content

6.6) 'sort', copying and 'sorted'


The sort() list method directly sorts the list it is applied on rather than returning a new list. Therefore if you want to keep the original list you have two options:

  • You can work on a copy of the list:
>>> planets=["Mercury","Venus","Earth","Mars"]
>>> planets_ordered=planets[:]   # a copy is done with [:]
>>> planets_ordered.sort()       # this will not affect the original list called 'planets'.

Visualise how copying works in action with this Pythontutor.com animation on list copying.
[advanced_iframe securitykey="cdcd195854f0661ec0561aa6e33a487eadfbcbcc" src="http://pythontutor.com/iframe-embed.html#code=planets1%3D%5B%22Mercury%22,%22Venus%22,%22Earth%22,%22Mars%22%5D%0Aplanets1.sort()+++%23+modifies+the+list+planets%0Aprint+planets1%0A%0A%23referencing%0Aplanets2%3D%5B%22Mercury%22,%22Venus%22,%22Earth%22,%22Mars%22%5D%0Aplanets_ref%3Dplanets2++%23+reference+the+list+planet%0Aplanets_ref.sort()%0Aprint+planets2++++++++%23+planets2+is+also+sorted%0A%0A%23copying%0Aplanets3%3D%5B%22Mercury%22,%22Venus%22,%22Earth%22,%22Mars%22%5D%0Aplanets_copy%3Dplanets3%5B%3A%5D+++%23+a+copy+is+done+with+%5B%3A%5D+%0Aplanets3.sort()++++++++%23+this+will+not+affect+planets.%0Aprint+planets_copy+++++%23+We+have+preserved+the+initial+order&cumulative=false&heapPrimitives=false&drawParentPointers=true&textReferences=false&showOnlyOutputs=false&py=2&curInstr=0"]

  • You can use the sorted function which takes oneĀ listĀ and returns a new list with the same elements sorted in (alphanumeric) order. So in the previous example:
>>> planets=["Mercury","Venus","Earth","Mars"]
>>> planets_ordered=sorted(planets[:])