Sorting 2D list with mixed types - Working with Python Lists: Medical Insurance Project

The exercise has you zip() two lists to a 2D list with the insurance cost the first element, the person’s name the second in each list. The 2D list, medical_records, looks like this:
[(13262.0, ‘Mohamed’), (4816.0, ‘Sara’), (6839.0, ‘Xia’), (5054.0, ‘Paul’), (14724.0, ‘Valentina’), (5360.0, ‘Jide’), (7640.0, ‘Aaron’), (6072.0, ‘Emily’), (2750.0, ‘Nikita’), (12064.0, ‘Paul’), (‘8320.0’, ‘Priscilla’)]

The exercise is to sort the 2D list by the float (insurance cost). I got the same answer as the hint but mine doesn’t work. Here is the code:

print("Here are the medical records sorted by insurance cost: " + str(medical_records))

Here is the error I’m getting:

TypeError: '<' not supported between instances of 'str' and 'float'

What am I missing on using the sort() method?

Bob C.

If you’re sorting a sequence of tuples then the sort will start by the first element of each tuple (using further elements only for any equal comparisons of the first element). See Sorting HOW TO — Python 3.9.6 documentation for more info.

It seems like all your elements are unique though so it might be worth checking the first elements of your tuples. Could there perhaps be more than one type used?

If it’s not entirely clear then the type() function and some judicious use of print might help you locate any trouble.

Found it! One element was a string that should have been a float. Your suggestion sent me in the right direction. Thank you!

1 Like