- Trending Categories
- Data Structure
- Operating System
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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])
- 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.
- Unpacking tuple of lists in Python
- Python to Find number of lists in a tuple
- Convert a list into tuple of lists in Python
- Python - Ways to iterate tuple list of lists
- Sort tuple based on occurrence of first element in Python
- Python Program to Merge Two Lists and Sort it
- Python program to sort a tuple by its float element
- Updating Lists in Python
- Merge Sort for Linked Lists using C++.
- Flatten tuple of List to tuple in Python
- Dividing two lists in Python
- Multi-dimensional lists in Python
- Tuple Division in Python
- Tuple multiplication in Python
- Python program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple