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])
xxxxxxxxxx
# You can use a lambda function, but you'll have to specify the index of the sorting key.
A = [[100, 'Yes'], [40, 'Maybe'], [60, 'No']]
print("Sorted List A based on index 0: % s" % (sorted(A, key=lambda x:x[0])))
B = [[2, 'Dog'], [0, 'Bird'], [7, 'Cat']]
print("Sorted List A based on index 1: % s" % (sorted(B, key=lambda x:x[1])))
# Also, you can use .sort() if you want to sort just by the first index
A = [[55, 90], [45, 89], [90, 70]]
A.sort()
print("New sorted list A is % s" % (A))
A.sort(reverse=True)
print("New reverse sorted list A is % s" % (A))
# You can even change the key sort, if you want to sort by length for example:
A = [[5, 90, 'Hi', 66], [80, 99], [56, 32, 80]]
A.sort(key=len) # <-
print("New sorted list A is % s" % (A))
xxxxxxxxxx
from operator import itemgetter
A = [[10, 8], [90, 2], [45, 6]]
print("Sorted List A based on index 0: % s" % (sorted(A, key=itemgetter(0))))
B = [[50, 'Yes'], [20, 'No'], [100, 'Maybe']]
print("Sorted List B based on index 1: % s" % (sorted(B, key=itemgetter(1))))
"""
Output:
Sorted List A based on index 0: [[10, 8], [45, 6], [90, 2]]
Sorted List B based on index 1: [[100, 'Maybe'], [20, 'No'], [50, 'Yes']]
"""
xxxxxxxxxx
l=[1,3,2,5]
l= sorted(l)
print(l)
#output=[1, 2, 3, 5]
#or reverse the order:
l=[1,3,2,5]
l= sorted(l,reverse=True)
print(l)
#output=[5, 3, 2, 1]
xxxxxxxxxx
l = [64, 25, 12, 22, 11, 1,2,44,3,122, 23, 34]
for i in range(len(l)):
for j in range(i + 1, len(l)):
if l[i] > l[j]:
l[i], l[j] = l[j], l[i]
print l
xxxxxxxxxx
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
xxxxxxxxxx
# define a list
my_list = [3, 1, 4, 2]
# sort the list
sorted_list = sorted(my_list)
print(sorted_list) # print as [1, 2, 3, 4]
# sort the list in place
my_list.sort()
print(my_list) # print as [1, 2, 3, 4]
# sort the list in descending order
sorted_list = sorted(my_list, reverse=True)
print(sorted_list) # print as [4, 3, 2, 1]
# sort the list in place in descending order
my_list.sort(reverse=True)
print(my_list) # print as [4, 3, 2, 1]