Python – Some useful list-of-tuples operations

Python 3.7

Sometimes we need to sort a list of tuples (or other list-type containers) according to their internal values.
For instance, you might have a list of tuples representing X,Y coordinates and need to sort that list according to the Y coordinate of the locations.
Using the sorted function with a lambda function as the supplied key argument can do that.
In this case, each tuple element is fed to the lambda function as the argument x and the function simply returns x[1], which is the second (Y) value within the tuple as the key for the sorting comparison:

sorted(my_tuple_list, key=lambda x: x[1])

Again, in a list of tuples (or other list-type containers), Sometimes we need to find the index of the first occurrence of a tuple that has a specific value as one of its elements.
This example will return the index of the first occurrence in the list of a tuple with the value 8 as its second element:


The zip function “decouples” the tuples into two lists one containing the tuples first element values and the second containing the tuples second element values.
The zip object is fed into a list function to be converted into a subscript-able list containing the 2 new lists, so now we can use the [1] index to access the list containing only the original tuples’s second elements, and use the index function to get the index of first occurrence of value 8.
> Note that the * operator isn’t a C like “pointer” operator..
Its a Python unpack operator needed to unpack the list of tuples to separate tuple arguments for the zip function.