close

How to sort a List of Lists in Python

Hello guys. How are you all? I hope you all fine. In this tutorial we will learn about how to sort a List of Lists in Python. so without wasting time lets learn about of this.

How to sort a List of Lists in Python

  1. sort a List of Lists in Python

    To sort a List of Lists in Python Use sort() you can sort a list of lists in python. It is very easy to use. Lets learn about of this by given example.A = [[45, 70], [45, 60], [90, 70]] A.sort() print("New sorted list A is % s" % (A))Output :New sorted list A is [[45, 60], [45, 70], [90, 70]]Thus you can sort a list by this.

  2. How to sort a List of Lists in Python

    To sort a List of Lists in Python Use itemgetter() you can sort a list of lists in python. It is very easy to use. Lets learn about of this by given example. from operator import itemgetter mylist = [[20, 15], [110, 2], [52, 6]] print("Sorted List is: % s" % (sorted(mylist, key=itemgetter(0)))) Output : Sorted List is: [[20, 15], [52, 6], [110, 2]]

  3. python sort list of lists

    To sort a List of Lists in Python Use sort() you can sort a list of lists in python. It is very easy to use. Lets learn about of this by given example.A = [[45, 70], [45, 60], [90, 70]] A.sort() print("New sorted list A is % s" % (A))Output :New sorted list A is [[45, 60], [45, 70], [90, 70]]Thus you can sort a list by this.

Method 1: Using sort()

By using sort() you can sort a list of lists in python. It is very easy to use. Lets learn about of this by given example.

A = [[45, 70], [45, 60], [90, 70]]
A.sort()
print("New sorted list A is % s" % (A))

Output :

New sorted list A is [[45, 60], [45, 70], [90, 70]]

Thus you can sort a list by this.

Method 2: Using itemgetter()

By using itemgetter() you can sort a list of lists. It is very easy to use. Lets learn about of this by given example.

from operator import itemgetter
mylist = [[20, 15], [110, 2], [52, 6]]
print("Sorted List is: % s" % (sorted(mylist, key=itemgetter(0))))

Output :

Sorted List is: [[20, 15], [52, 6], [110, 2]]

Method 3: Using lambda

By using lambda you can sort a list of lists. It is very easy to use. Lets learn about of this by given example.

mylist = [[100, 100], [40, 60], [60, 50]]
print("My Sorted List is : % s" % (sorted(mylist, key=lambda x:x[0])))

Output :

My Sorted List is : [[40, 60], [60, 50], [100, 100]]

Conclusion

It’s all About this Tutorial. Hope all methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you?

Also, Read

Leave a Comment