Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort a list of lists using descending order, and then if there is a tie breaker, use descending order on another index in python

master_list = [["Hi", 2.00],["Hey", 6.01],["Hello", 9.56], ["How", 6.01]]
master_list.sort(key=lambda x: -(x[1], -x[0]))

I tried using this function to sort the master_list in descending order by the number, and if there is a tie, descending order by the string.
However, I get the error "TypeError: bad operand type for unary -: ‘str’
I don’t know what I am doing wrong to get this error. How do I sort the list?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It is because you are applying a negation (-) on a tuple a string. Using sorted function, you can use reverse=True to sort the array in descending order.

sorted(master_list, key=lambda x: (x[1], x[0]), reverse=True) 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading