how.wtf

Sort a list of tuples by an item in Python

· Thomas Taylor

Python has native sort capabilities available for use. You can sort a list of objects by leveraging one of the method specified below.

The questions that this post addresses:

  1. Q: How do you sort a list of tuples by the 1st item?
  2. Q: How do you sort a list of tuples by the 2nd item?
  3. Q: How do you sort a list of tuples in reverse?

sorted() function

The sorted() function returns a sorted iterable object, such as a list, in a specified order. It does not modify the list in place.

By default, the sorted() function evaluates the items to determine their order. In the example below, the lexical ordering of the 1st index determines the sorted list.

1lst = [("val2", 2), ("val1", 1)]
2print(sorted(lst))
3# Output: [('val1', 1), ('val2', 2)]

If the 1st elements are identical, the 2nd element determines the ordering:

1lst = [("val1", 2), ("val1", 1)]
2print(sorted(lst))
3# Output: [('val1', 1), ('val2', 2)]

You can optionally specify an index to sort on using a lambda function:

1lst = [("val2", 2), ("val1", 1)]
2print(sorted(lst, key=lambda x: x[1]))
3# Output: [('val1', 1), ('val2', 2)]

Reverse as well:

1lst = [("val2", 2), ("val1", 1)]
2print(sorted(lst, key=lambda x: x[1], reverse=True))
3# Output: [('val2', 2), ('val1', 1)]

Using itemgetter instead of lambda:

1from operator import itemgetter
2lst = [("val1", 1), ("val2", 2)]
3print(sorted(lst, key=itemgetter(1), reverse=True))
4# Output: [('val2', 2), ('val1', 1)]

list.sort() function

The list.sort() method sorts a list in place and does not return a value.

Similar to the sorted() function, it uses the lexical ordering of the 1st index to determine the sorted list.

1lst = [("val2", 2), ("val1", 1)]
2lst.sort()
3print(lst)
4# Output: [('val1', 1), ('val2', 2)]

If the 1st elements are identical, the 2nd element determines the ordering:

1lst = [("val1", 2), ("val1", 1)]
2lst.sort()
3print(lst)
4# Output: [('val1', 1), ('val2', 2)]

You can optionally specify an index to sort on using a lambda function:

1lst = [("val2", 2), ("val1", 1)]
2lst.sort(key= lambda x: x[1])
3print(lst)
4# Output: [('val1', 1), ('val2', 2)]

Reverse as well:

1lst = [("val1", 1), ("val2", 2)]
2lst.sort(key= lambda x: x[1], reverse=True)
3print(lst)
4# Output: [('val2', 2), ('val1', 1)]

Using itemgetter instead of lambda:

1from operator import itemgetter
2lst = [("val1", 1), ("val2", 2)]
3lst.sort(key=itemgetter(1), reverse=True)
4print(lst)
5# Output: [('val2', 2), ('val1', 1)]

#Python  

Reply to this post by email ↪