Medical Ins. Costs, List and sorting question

BUILD A RECOMMENDER SYSTEM

Working with Python Lists: Medical Insurance Costs Project

Sorting Lists
I need to sort a 2d list that have to different data: Name and cost of insurance
when i write 'medical_records.sort() it sorted by name but i need to sorted by cost insurance which is the second data
example [ (‘Moony’, 3500), (‘Runa’, 5000)]

1 Like

A few things here…

  • please remember to include a link to the lesson to which your question is regarding.
  • If you could please post your formatted code. Select the </> button or refer to this post here.

Did you use .zip() to combine the two lists? You can always re-arrange the order of the two lists in the .zip()

Perhaps these posts will help you? (this question comes up often and is available via :mag: )

Or,

There is also the Python docs to consider:

So…Considering all of this. You could sort it by using a lambda function and index. (Edit: I’m not sure if you’ve covered lambda functions yet).

Ex Hint:

Summary
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]

medical_records = list(zip(insurance_costs, names))
print(medical_records)

medical_records.sort(key= lambda x: x[0])
print(medical_records)

>>> [(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')]

>>>[(2750.0, 'Nikita'), (4816.0, 'Sara'), (5054.0, 'Paul'), (5360.0, 'Jide'), (6072.0, 'Emily'), (6839.0, 'Xia'), (7640.0, 'Aaron'), (12064.0, 'Paul'), (13262.0, 'Mohamed'), (14724.0, 'Valentina')]

thank you very much for the answer. The problem was that it show me i needed to put the insurance costs first and then the name but i will chech the sorting HOW TO to learn how to modifie the list in-place.
Next time i will remember to put the link :star_struck:

1 Like

Sure thing. :slight_smile:
Key takeaways:
.sort() sorts the list in place. .sorted() is a built in function and it works with any iterable and produces a new list. Both have a key parameter, ‘to specify a function (or other callable) to be called on each list element prior to making comparisons.’ (docs).