How to sort a list or set based on second item in python | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to sort a list or set based on second item in python

a list might contain a list in itself so how to sort a list based on the second item in the inner list

19th May 2018, 8:06 AM
Suhail Ahmad
Suhail Ahmad - avatar
4 Answers
+ 2
[["A",10],["B",5]] the text below should be the output...the sorting should happen based on second element [["B",5],["A",10]]
20th May 2018, 3:59 AM
Suhail Ahmad
Suhail Ahmad - avatar
+ 1
consider one list here, l = [12,10,20,39,[1,6,11,19,22],23,5,6] Can you please tell how it looks a like after sort? inner list may have smaller/bigger value than outer list. Could you please tell why do you need such a requirement?
20th May 2018, 3:23 AM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar
+ 1
you can iterate over list and copy into dictionary and sort dictionary per value and again iterate over dictionary and restore the sorted things into list. make sense?
20th May 2018, 4:21 AM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar
+ 1
print(sorted([['A',10],['B',5]], key=lambda colonnes: colonnes[1]))
20th May 2018, 11:02 PM
Nicolas MALET
Nicolas MALET - avatar