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']] """
Here is what the above code is Doing:
1. The sorted() function takes a list as an argument and returns a sorted list.
2. The key=itemgetter(0) argument tells the sorted() function to sort the list based on the first element of each list.
3. The key=itemgetter(1) argument tells the sorted() function to sort the list based on the second element of each list.