Does the sort() function work if a list contains different types?


#1

Question

In this exercise, the sort() function is used to sort the contents of lists of like data types. What will sort() do if the list contains different data types?

Answer

Python does not guarantee that the sort() function will work if a list contains items of different data types. As long as the items can be compared using the < comparison operator, an attempt will be made to sort the list. Otherwise, an error or exception may be generated.

In the example below, the list contains a mixture of string, integer and decimal numbers. The sort() function is able to sort the list putting the numerical values before the strings.

mixed = ['Adam', 1, 'Sam', 5, 'George', 3, 'dog', -2.5,  'cat']

mixed.sort()

# Prints - [-2.5, 1, 3, 5, 'Adam', 'George', 'Sam', 'cat', 'dog']
print(mixed)