Write a Python Program to Sort The List According to The Second Element in Sublist

Given a nested list of numbers you have to sort the list according to the second element of the number in the Sub list.

 

Write a Python Program to Sort The List According to The Second Element in Sublist



 

For example let take a sample sub list  as shown below

my_list = [[4, 5, 50], [1, 2, 3, 100], [6, 90], [7, 8, 9, 10]]

 

The Sub list contained in the policies

[4, 5, 50]
[1, 2, 3, 100]
[6, 90]
[7, 8, 9, 10]

 

The second element of each sublist will be

5
2
90
8

 

Now based on this we have to solve the sub list in a nested list.  if we try to sort it will be as shown below

2
5
8
9

 

Sorted sub list will looks like

[1, 2, 3, 100]
[4, 5, 50]
[7, 8, 9, 10]
[6, 90]

 

at the end nested list will be shown below

[[1, 2, 3, 100], [4, 5, 50], [7, 8, 9, 10], [6, 90]]





Write a Python Program to Sort The List According to The Second Element in Sublist


Let's write a function that will return the second element  of each of the sublists that we pass as an argument to the function.  To return the second element  we need to refer the index as 1 and return it


def return_second_item(mysublist):
    return mysublist[1]



let a take above list example and initialize nested list
 
my_list = [[4, 5, 50], [1, 2, 3, 100], [6, 90], [7, 8, 9, 10]]




Use another variable and  call the sorted function,  pass the nested list and function name as arguments to the sorted function call.

Sorted function returns a list that is father of according to the second element of a  nested list.

new_list = sorted(my_list, key=return_second_item)
print(new_list)



 

Final Program
=============================

def return_second_item(mysublist):
    return mysublist[1]


my_list = [[4, 5, 50], [1, 2, 3, 100], [6, 90], [7, 8, 9, 10]]

new_list = sorted(my_list, key=return_second_item)
print(new_list)




INPUT LIST:
======================================

[[4, 5, 50], [1, 2, 3, 100], [6, 90], [7, 8, 9, 10]]




OUTPUT
======================================

[[1, 2, 3, 100], [4, 5, 50], [7, 8, 9, 10], [6, 90]]




Conclusion : Try to run the program by modifying the nested list second item and note down the new nested list.



Post a Comment

0 Comments