Sort lists in tuple in Python

When it is required to sort the lists in a tuple, the tuple() method, the sorted() method and a generator expression can be used.

The sorted() method is used to sort the elements of a list. It is a built-in function that returns the sorted list without modifying the original.

Generator expression is a simple way of creating iterators. It automatically implements a class with __iter__() and __next__() methods and keeps track of the internal states, as well as raises StopIteration exception when no values are present that could be returned.

The tuple() method takes an iterable as argument, and converts it into a tuple type.

Example

Here's how to sort each list within a tuple ?

my_tuple = ([4, 55, 100], [44, 55, 67], [7, 86, 0])

print("The tuple of list is")
print(my_tuple)

my_result = tuple((sorted(sub) for sub in my_tuple))

print("The tuple of list after sorting is :")
print(my_result)
The tuple of list is
([4, 55, 100], [44, 55, 67], [7, 86, 0])
The tuple of list after sorting is :
([4, 55, 100], [44, 55, 67], [0, 7, 86])

Alternative Approach Using List Comprehension

You can also use list comprehension with tuple() for the same result ?

my_tuple = ([12, 3, 45], [88, 1, 23], [99, 5, 77])

print("Original tuple:")
print(my_tuple)

# Using list comprehension
sorted_tuple = tuple([sorted(lst) for lst in my_tuple])

print("Sorted tuple:")
print(sorted_tuple)
Original tuple:
([12, 3, 45], [88, 1, 23], [99, 5, 77])
Sorted tuple:
([3, 12, 45], [1, 23, 88], [5, 77, 99])

How It Works

  • A tuple containing lists is created and displayed on the console
  • Each list is iterated over using a generator expression
  • The sorted() method sorts each individual list
  • The generator expression is converted back into a tuple using tuple()
  • The final result contains the same lists but each one is sorted internally

Conclusion

Use generator expressions with tuple(sorted(sub) for sub in my_tuple) to sort each list within a tuple. This approach is memory-efficient and maintains the tuple structure while sorting individual lists.

Updated on: 2026-03-25T17:30:37+05:30

415 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements