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?
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 unable to sort the list since numbers and strings cannot be compared.
mixed = ['Adam', 1, 'Sam', 5, 'George', 3, 'dog', -2.5, 'cat'] mixed.sort() #Results in: TypeError: '<' not supported between instances of 'int' and 'str'
Note: This used to work in Python 2, however with the move to Python 3 it no longer does.