How do I sort a nested list by second element?

Python | Sort a list according to the second element in sublist

In this article, we will learn how to sort any list, according to the second element of the sublist present within the main list. We will see two methods of doing this. We will learn three methods of performing this sort. One by the use of Bubble Sort, second by using the sort[] method and last but not the least by the use of sorted[] method. In this program, we have sorted the list in ascending order.
Examples:

Input : [['rishav', 10], ['akash', 5], ['ram', 20], ['gaurav', 15]] Output : [['akash', 5], ['rishav', 10], ['gaurav', 15], ['ram', 20]] Input : [['452', 10], ['256', 5], ['100', 20], ['135', 15]] Output : [['256', 5], ['452', 10], ['135', 15], ['100', 20]]

Different ways of Sorting the list of lists in python

  1. Sorting the data by 1st column
  2. Sorting the data using any other column
  3. Sorting the list of lists by length
  4. How to sort the list of lists by the sum of elements
  5. Sorting the list of lists in descending order
  6. Creating our own Program to sort the list of lists in Python

1. Sorting the data by 1st column

To sort the data according to the 1st columns in ascending order.

list1=[['Bajaj Pulsar','220 F',40],['Yamaha','YZF R15 Ver 3.0',45],['TVS Apache','rtr 160',50]] # Using the key parameter of sort method. # if we use the sort method, the sorting take place in the list itself list1.sort[] print[list1]

Output-

[['Bajaj Pulsar', '220 F', 40], ['TVS Apache', 'rtr 160', 50], ['Yamaha', 'YZF R15 Ver 3.0', 45]]

When we want to sort the list according to the first columns, we do not need to do anything special. We just need to do everything as usual. Let us see another way of achieving the same.

The above method sorts the data in the original list itself. If we do not wish to make the changes in the original list, we can use the below method.

list1=[['Bajaj Pulsar','220 F',40],['Yamaha','YZF R15 Ver 3.0',45],['TVS Apache','rtr 160',50]] print[sorted[list1]] # lets see if our original list has changed or not print[list1]

[['Bajaj Pulsar', '220 F', 40], ['TVS Apache', 'rtr 160', 50], ['Yamaha', 'YZF R15 Ver 3.0', 45]]

Now let us see the naive method using to achieve our goal.

list1=[['Bajaj Pulsar','220 F',40],['Yamaha','YZF R15 Ver 3.0',45],['TVS Apache','rtr 160',50]] # Iterating through one the list. #There is no element with which we will compare the last element, #so we are not including the last element for i in range[len[list1]-1]: # if the next element is greater then the next element, swap it. if list1[i][0]>list1[i+1][0]: list1[i][0],list1[i+1][0]=list1[i+1][0],list1[i][0] print[list1]

[['Bajaj Pulsar', '220 F', 40], ['TVS Apache', 'YZF R15 Ver 3.0', 45], ['Yamaha', 'rtr 160', 50]]

How do you sort a list by second element in Python?

Use a lambda function as an argument to sort[] to sort a list of tuples by the second value. Call list. sort[key=None] with list as a list of tuples and key set to lambda x: x[1] to sort list by the second element of each tuple.

How do I sort a nested list in Python?

Sorting and Grouping Nested Lists in Python

  1. Use a function to reorder the list so that I can group by each item in the list. For example I’d like to be able to group by the second column [so that all the 21’s are together]
  2. Use a function to only display certain values from each inner list.

Python sort nested list by first and second element

2 tháng trước

Sorting the list of numbers or characters is easy. We can use sort[] method or sorted[] built-in function.

In this tutorial, we want to sort a list of tuples by first and second value in the tuple.

Example:

Lets consider the tuple list having programming languages and its first appearance year.

[[1985, "C++"], [1995, "Java"], [1990, "Python"]]

Prerequisite:

  • Python List Basics
  • Sorting Python List
  • Python Lambda Function

Sort Tuple List by First Element in Python

prog_yr_appeared = [[1985, "C++"], [1995, "Java"], [1990, "Python"]] #Ascending Order print["Ascending Order"] prog_yr_appeared.sort[key= lambda x: x[0]] print[prog_yr_appeared] #Descending Order print["Descending Order"] prog_yr_appeared.sort[key= lambda x: x[0], reverse=True] print[prog_yr_appeared]

Note: We are setting a reverse option as True to sort the list in descending order.

Output:

Ascending Order [[1985, 'C++'], [1990, 'Python'], [1995, 'Java']] Descending Order [[1995, 'Java'], [1990, 'Python'], [1985, 'C++']]

It Python trick can be very useful for solving competitive coding challenges. One such example is, I was asked to write a program for merging overlapping intervals in Bijus interview. Here, we have to sort the intervals [list of tuples] by their first value.

Sort Tuple List by Second Element in Python

With a slight change in lambda function, we can sort the list of tuples by the second value in the tuple.

Here is the Python code.

prog_yr_appeared = [[1985, "C++"], [1995, "Java"], [1990, "Python"]] #Ascending Order print["Ascending Order"] prog_yr_appeared.sort[key= lambda x: x[1]] print[prog_yr_appeared] #Descending Order print["Descending Order"] prog_yr_appeared.sort[key= lambda x: x[1], reverse=True] print[prog_yr_appeared]

Output:

Ascending Order [[1985, 'C++'], [1995, 'Java'], [1990, 'Python']] Descending Order [[1990, 'Python'], [1995, 'Java'], [1985, 'C++']]

There can be a nested list instead of a list of tuples. In either way, you have to solve this problem using same method. You can read the difference between list and tuple in Python.

This is one of the very tricky questions asked in Python interviews. This method to sort tuple list by first and second element in Python can also help you in solving coding challenge questions.

Pythonpython list

Video liên quan

Video liên quan

Bài mới nhất

Chủ Đề