. Advertisement .
..3..
. Advertisement .
..4..
Computers are mostly used to store information and extract information from it. Python is one of the most powerful programming languages. We can use Python to get computers to do most of the routine processes. One of the most effective data structures in Python is a list. By placing each element of the list in ascending or descending order, depending on the criteria, we may sort a list in Python. This blog is all about Tips On Sorting a List of Lists in Python.
How Can You sort a List of Lists in Python?
Approach 1: Utilize sort()
In Python, you can sort a List of Lists. In Python, users can sort a list of lists utilizing sort(). It’s very simple to use. Let’s take a look at an example of this.
A = [[45, 70], [45, 60], [90, 70]]
A.sort()
print("New sorted list A is % s" % (A))
Result:
New sorted list A is [[45, 60], [45, 70], [90, 70]]
As a result, you can use this to sort a list.
Approach 2: Utilize sorted()
Another solution for you to sort a List of Lists in Python is utilizing the sorted().
The initial list is changed when the sort() method is used. You can use the sorted() function to prevent this. A list is passed to the sorted() method, which creates a new list with the members of the input list in the following order.
myList = [1, 2, 5, 3, 77, 12, 104, 34]
print("The input list is:", myList)
newList = sorted(myList)
print("The sorted list is:", newList)
Result:
The input list is: [1, 2, 5, 3, 77, 12, 104, 34]
The sorted list is: [1, 2, 3, 5, 12, 34, 77, 104]
myList = [[504, 1, 2, 12], [5, 3, 77], [12, 104, 34]]
print("The input list is:", myList)
newList=sorted(myList)
print("The sorted list is:", newList)
The input list is: [[504, 1, 2, 12], [5, 3, 77], [12, 104, 34]]
The sorted list is: [[5, 3, 77], [12, 104, 34], [504, 1, 2, 12]]
Approach 3: Utilize itemgetter()
In Python, users can also sort a list of lists utilizing itemgetter(). It’s very simple to use. Let’s take a look at an example of this.
from operator import itemgetter
mylist = [[20, 15], [110, 2], [52, 6]]
print("Sorted List is: % s" % (sorted(mylist, key=itemgetter(0))))
Result:
Sorted List is: [[20, 15], [52, 6], [110, 2]]
Approach 4: Utilize lambda
In Python, users can also sort a list of lists utilizing itemgetter(). The lambda functions can be used in this circumstance. It’s very simple to use. Let’s take a look at an example of this.
mylist = [[100, 100], [40, 60], [60, 50]]
print("My Sorted List is : % s" % (sorted(mylist, key=lambda x:x[0])))
Result:
My Sorted List is : [[40, 60], [60, 50], [100, 100]]
Conclusion
Sorting a List of Lists in Python is a confusing problem. We hope this blog has helped clear the air around how to do it. If you have more questions about this topic, please leave a comment below. Thank you for reading; we are always excited when one of our posts can provide useful information on a topic like this!
Read more
Leave a comment