Help with using sorted in python pls

Hello, I am trying to sort a list by the second element index[1] of the tuple but it’s not working. in this example. i want to sort by insurance cost instead of name

https://www.codecademy.com/paths/data-analyst/tracks/dacp-python-fundamentals/modules/dscp-python-lists/projects/ds-python-lists2-project

medical_records= list(zip(names, insurance_costs))

#print(medical_records)

sorted(medical_records, key=lambda record:record[1])

print("Here are the medical records sorted by insurance cost: " + str(medical_records))
Thank you in advance!

The sorted function does not act on the existing list. It creates a new one. You can either use the .sort() method of the existing list or you can work with what sorted returns.

I am stuck on the same step of the same exercise. I tried both of the following, but it gives a type error. My second solution is actually exactly what is suggested in the “Hint” for that step.

medical_records = list(zip(insurance_costs, names))
medical_records_sorted = sorted(medical_records)

OR
medical_records = list(zip(insurance_costs, names))
medical_records.sort()

Thanks again!

It’s worth having a quick nose through- How to ask good questions (and get good answers), particularly the bits about code formatting and including your code and the error message.

At present you mention a type error but not what line it came from and without more of the code it’s impossible to guess why. A little description goes a long way :slightly_smiling_face:.

1 Like

Thanks for your patience – I’ll take a look!

1 Like

Trying again! This is the same exercise OP was talking about –
https://www.codecademy.com/paths/data-science/tracks/dscp-python-fundamentals/modules/dscp-python-lists/projects/ds-python-lists2-project

Here is the code that was provided at the start of the exercise, as well as all the lines I wrote before I got the error:

names = ["Mohamed", "Sara", "Xia", "Paul", "Valentina", "Jide", "Aaron", "Emily", "Nikita", "Paul"]
insurance_costs = [13262.0, 4816.0, 6839.0, 5054.0, 14724.0, 5360.0, 7640.0, 6072.0, 2750.0, 12064.0]

# Add your code here
names.append("Priscilla")
insurance_costs.append("8320.0")
medical_records = list(zip(insurance_costs, names))
print(medical_records)
num_medical_records = len(medical_records)
print("There are "+str(num_medical_records)+" medical records.")
first_medical_record = medical_records[0]
print("Here is the first medical record: "+str(first_medical_record))

At this point, the instructions in the exercise ask you to sort medical_records

I tried a couple of ways, including the suggestion in the hint:

medical_records.sort()
medical_records_sorted = sorted(medical_records)

Both produced the same type error:

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

In the end, I could finish the exercise with an unsorted list, but I would like to know why it didn’t work. Thanks!

1 Like

Thanks, that’s ample detail :grinning:.

You’ll catch an error like that with something like [3, "3"].sort(). The sorting algorithm relies on certain operations that aren’t supported between certain different types in Python, for example: 3 < "3".

This is a bit more complex with the tuples you have but as per- Sorting HOW TO — Python 3.9.5 documentation you’re sorting by the first element of each tuple at first. So at some point a string and an int must be compared. Can you spot where?

Hint
# Try the following to see if you can spot the odd one out-
print(insurance_costs)
2 Likes

Yay, thanks! I found it – I had appended an integer as a string. Now it works. Really appreciate your patient help :grinning_face_with_smiling_eyes:

1 Like

Hi, I have a similar issue… I understand that I have to use a key in the sort() function and so I am able to sort the list by the insurance cost.

However, the exercise shows that insurance cost should now come before name - since I zipped the original two lists with the name first and insurance cost second, is there a way to reverse the order within each nested list with some funky code other than just me reversing the order in the original zip()? If so, what terminology should I be Googling?

names = ["Mohamed", "Sara", "Xia", "Paul", "Valentina", "Jide", "Aaron", "Emily", "Nikita", "Paul"] insurance_costs = [13262.0, 4816.0, 6839.0, 5054.0, 14724.0, 5360.0, 7640.0, 6072.0, 2750.0, 12064.0] # Add your code here names.append("Priscilla") insurance_costs.append(8320.0) medical_records = list(zip(names, insurance_costs)) print(medical_records) num_medical_records = len(medical_records) print("There are " + str(num_medical_records) + " medical records.") first_medical_records = medical_records[0] print("Here is the first medical record: " + str(first_medical_records)) medical_records.sort(key = lambda x: x[1]) print("Here are the medical records sorted by insurance cost: " + str(medical_records))

Thank you in advance!

Ok - I think think the video about Tuples, that followed, explained that I can’t change the order through code because it’s immutable. My only option is to change the order when I zip().

So what if you didn’t want to change the order of the inputs in the zip function in this example. Is there a way to specify in the .sort() function which input you want to sort by?

While we cannot mutate a zip object or its items, we can sort by either member. We use sorted() in this instance since it returns a new list rather than sorting in place (which it cannot do with a zip object, or a tuple). Hopefully this meets with your question:

a = [4, 6, 1, 7, 2, 3, 8, 9, 5]
b = [17, 19, 12, 13, 16, 18, 11, 14, 15]

Those were sorted to start but then I shuffled them both for better demonstration of how sorted() works.

print (sorted(zip(a, b), key=lambda x: x[0]))
[(1, 12), (2, 16), (3, 18), (4, 17), (5, 15), (6, 19), (7, 13), (8, 11), (9, 14)]

print (sorted(zip(a, b), key=lambda x: x[1]))
[(8, 11), (1, 12), (7, 13), (9, 14), (5, 15), (2, 16), (4, 17), (3, 18), (6, 19)]

See how each case is ordered after sorting? In the first example the first member is in order, in the second example the second member is in order.

Note that the first example doesn’t need a key argument since sorted() defaults to the first member.

print (sorted(zip(a, b)))
[(1, 12), (2, 16), (3, 18), (4, 17), (5, 15), (6, 19), (7, 13), (8, 11), (9, 14)]

Note that we can have more than two lists in a zip object.

c = ['h', 'j', 'f', 'i', 'b', 'a', 'c', 'd', 'e', 'g']

print (sorted(zip(c, b, a), key=lambda x: x[2]))
[('f', 12, 1), ('b', 16, 2), ('a', 18, 3), ('h', 17, 4), ('e', 15, 5), ('j', 19, 6), ('i', 13, 7), ('c', 11, 8), ('d', 14, 9)]
print (sorted(zip(c, b, a)))
[('a', 18, 3), ('b', 16, 2), ('c', 11, 8), ('d', 14, 9), ('e', 15, 5), ('f', 12, 1), ('h', 17, 4), ('i', 13, 7), ('j', 19, 6)]