How does Python decide the default sort order?


#1

In the example code:

animals = ["cat", "ant", "bat"]
animals.sort()

for animal in animals:
  print animal

Why does “animals.sort()” sort the list in alphabetical order by default? It seems to me that there’s no instruction as to how I want python to sort the list?


FAQ: Learn Python: Python Lists and Dictionaries - More with 'for'
#2

In the abscence of any directive arguments, Python defaults to ascending sort.

Character values are sorted by ordinal, lowest first.

Example of a directive argument…

animals.sort(reverse=True)
>>> animals = ["cat", "ant", "bat"]
>>> animals.sort()
>>> for animal in animals:
  print (animal)

  
ant
bat
cat
>>> animals = ["cat", "ant", "bat"]
>>> animals.sort(reverse=True)
>>> for animal in animals:
  print (animal)

  
cat
bat
ant
>>> 

Please help us to insert this topic in the correct category by posting the URL of the exercise. Thanks.


#4