VOOZH about

URL: https://www.geeksforgeeks.org/python/python-order-tuples-by-list/

⇱ Python - Order Tuples by List - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python - Order Tuples by List

Last Updated : 3 Nov, 2025

Given a list of tuples, our task is to reorder it according to the sequence defined in another list. This can be useful in data processing, sorting, and mapping tasks.

Example:

Input = [('Gfg', 10), ('best', 3), ('CS', 8), ('Geeks', 7)], ord_list = ['Geeks', 'best', 'CS', 'Gfg'] 
Output = [('Geeks', 7), ('best', 3), ('CS', 8), ('Gfg', 10)] 

Using dict() + List Comprehension

Convert the list of tuples into a dictionary for fast key-value access, then use list comprehension to reorder tuples based on the given list sequence.


Output
[('Geeks', 2), ('best', 9), ('CS', 10), ('Gfg', 3)]

Explanation:

  • dict(t): converts the list of tuples into a dictionary for quick key-value lookup.
  • [(key, temp[key]) for key in l]: creates a new list of tuples arranged according to the order in o1.

Using setdefault() + sorted() + lambda

This method builds a position map for elements using setdefault() and then sorts tuples with sorted() and a lambda based on that predefined order.


Output
[('Geeks', 2), ('best', 9), ('CS', 10), ('Gfg', 3)]

Explanation:

  • idx.setdefault(ele, []).append(key): Maps each name to its order index.
  • sorted(t, key=lambda ele: temp[ele[0]].pop()): Sorts tuples by that index

Using reduce() Function

This method uses functools.reduce() to iterate over the order list and sequentially accumulate tuples from the main list in the desired order.


Output
[('Geeks', 2), ('best', 9), ('CS', 10), ('Gfg', 3)]

Explanation: reduce(lambda acc, key: acc + [ele for ele in t if ele[0] == key], l, []): iterates through each element in l, finds matching tuples in t, and accumulates them in order.

Using lambda with sorted()

This method sorts the tuples based on the position of their first element in the reference list using a lambda function with sorted().


Output
[('Geeks', 7), ('best', 3), ('CS', 8), ('Gfg', 10)]

Explanation: sorted(t, key=lambda x: l.index(x[0])): sorts t based on each tuple’s first element’s position in l.

Using itemgetter()

This method sorts tuples based on a specific element index using itemgetter() from the operator module for cleaner and faster key access.


Output
[('Geeks', 2), ('Gfg', 3), ('best', 9), ('CS', 10)]

Explanation:sorted(l1, key=itemgetter(1)): sorts the list based on the second element (index 1) of each tuple.

Related Articles:

Comment