



Note: The key doesn't correspond to the first value of the tuple, which is oftentimes referred to as a "key" as in, a "key-value" pair. Typically, it's easiest to map the key to another item in the list of tuples, through a lambda function: tuple_list = To alter the item based on which tuples are sorted, without changing the tuples themselves - you can specify any item in a tuple instead as the key argument. Since tuples are sorted by key, this list of tuples is sorted lexicographically, by the strings used as the keys. Or, to sort a list of tuples with sorted(): sorted_tuples = sorted(tuple_list) For instance, say you had a leaderboard of preferred programming languages, stored in a tuple of (language, rank) format - you might want to sort them in order of rank: tuple_list = Or, with sorted(): sorted_list = sorted(int_list) Integers are more straightforward in their comparison with the > operator: int_list = Other than the capital letters - the rest of the strings are sorted in ascending dictionary order! Sort List of Integers I has a lesser lexicographical value than blue, even though b should be before i in the dictionary, because capital letters always have a lesser lexicographic value than lowercase letters. The same logic is applied to the sorted() function: sorted_list = sorted(string_list) Strings are sorted lexicographically, when compared with the > operator: string_list = Strings are compared differently than integers, which are in turn, compared differently to custom objects, for instance. The way comparisons are done depends on the data type of the elements of the list. However, sorted() creates a copy of the list we supply, sorts the copy, and returns it - leaving the original intact: # Sorts copy of `my_list` and returns it The sorted() function works in much the same way as the sort() function does - and also accepts the same arguments. To sort in descending order, you can supply the reverse=True argument to the function: my_list.sort(reverse= True) # my_list is sorted in-place - the original list is changed
