xxxxxxxxxx
# Python code to sort the lists using the second element of sublists
# Inplace way to sort, use of third variable
def Sort(sub_li):
l = len(sub_li)
for i in range(0, l):
for j in range(0, l-i-1):
if (sub_li[j][1] > sub_li[j + 1][1]):
tempo = sub_li[j]
sub_li[j]= sub_li[j + 1]
sub_li[j + 1]= tempo
return sub_li
# Driver Code
sub_li =[['rishav', 10], ['akash', 5], ['ram', 20], ['gaurav', 15]]
print(Sort(sub_li))
xxxxxxxxxx
name_age = [["A", 7], ["B", 5], ["C", 35]]
name_age.sort(key=lambda age: age[1])
#name_age.sort(key=lambda age: age[1], reverse = True)
print(name_age)
#sorts according to the 1th value of the inner loop
xxxxxxxxxx
my_list1 =[("d",4),("a",1),("e",5),("b",2),("c",3)]
my_list2 =[["d",4],["a",1],["e",5],["b",2],["c",3]]
# The 'sort' method will produce similar results
# for both list of lists and list of tuples
# Ascending pair based on second element: 1,2,3,4,5
my_list1.sort(reverse = False, key = lambda element: element[1])
# Descending pair based on second element: 5,4,3,2,1
my_list2.sort(reverse = True, key = lambda element: element[1])