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.

Generator 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.

A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).

Below is a demonstration of the same −

Example

Live Demo

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)

Output

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])

Explanation

  • A tuple of list is created, and is displayed on the console.
  • It is iterated over, and sorted using the 'sorted' method.
  • It is converted into a tuple using the 'tuple' method.
  • This is all done using a generator expression.
  • This is assigned to a value.
  • It is displayed on the console.

Updated on: 12-Mar-2021

220 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements