How to Sort a List of Tuples Based on Multiple Elements
Suppose we have a list of tuples that we want to sort with multiple conditions.
lst_of_tuples = [(4, 5), (2, 15), (3, 10), (1, 5)]
Suppose we want to sort based on the second element in the tuple, then the first. This means that when the second element in the tuple is the same, we want to resort to comparing the first element.
In the scenario above, we would first sort by the second element:
5, 5, 10, 15.
We have two
5s, so we will then sort those two tuples by the first element:
sorted_lst_of_tuples = [(1, 5), (4, 5), (3, 10), (2, 15)]
To do this, we can use the
key parameter in
sorted(). We can specify the priority of the sorting element by returning a tuple containing the sort order.
sorted_lst_of_tuples = sorted(lst_of_tuples, key=lambda x: (x, x))
x represents each list element. In our case, a single tuple.
x represents the second element in the tuple while
x represents the first element.
More Python Articles
- How to Start an HTTP Server in Python
- How to Get All Keys with the Highest Value in Python
- How to Check if a Tuple Exists in a List in Python
- How to Sort a List of Dictionaries By Field in Python
- How to Sort a Dictionary by Value in Python
- How to Flatten a 2D List in Python
- How to Remove Duplicates from a List in Python
- How to Set Multiple Values of a List in Python
- How to Remove the Last N Elements of a List in Python
- How to Get the ASCII Value of a Character in Python
- How to Loop Over a String in Reverse in Python
- How to Create a Two Dimensional List in Python
- How to Migrate Data from MongoDB to Elasticsearch in Python
- How to Add Key-Value to Dictionary During List Comprehension in Python
- How to Fix "datetime is not JSON serializable" TypeError in Python
- How to Remove a Key From a Dictionary in Python
- Encoding and Decoding Bytes Explained
- How to Paginate/Scroll Elasticsearch Data using Python
- How to Print Without Newline in Python 3
- How to Get the Key with the Maximum Value in Python
- List Comprehension in Python Explained Visually
- How to Check if a String Contains Another String in Python
- What is Enumerate in Python?
- What is the Difference Between List and Tuple in Python?