- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python program to sort a list according to the second element in sublist
List is given, our task is to sort a list according to the second element in the sublist. Here we apply simple bubble sort.
Input [['CCC', 15], ['AAA', 10], ['RRRR', 2],['XXXX', 150]] Output [['RRRR', 2], ['AAA', 10], ['CCC', 15], ['XXXX', 150]]
Step 1: Given a list. Step2: We have tried to access the second element of the sublists using the nested loops. Step 3: Traverse through all array elements. Step 4: Last i elements are already in place. Step 5: traverse the array from 0 to n-i-1. Step 6: Swap if the element found is greater than the next element.
# Python program to sort the lists using the second element of sublist # In place way to sort, use of third variable. def sortlist(A): l = len(A) for i in range(0, l): for j in range(0, l-i-1): if (A[j] > A[j + 1]): tempo = A[j] A[j]= A[j + 1] A[j + 1]= tempo return A # Driver Code A =[['AAA', 10], ['CCC', 15], ['RRRR', 2], ['XXXX', 150]] print(sortlist(A))
[['RRRR', 2], ['AAA', 10], ['CCC', 15], ['XXXX', 150]]
- Python program to sort a list according to the second element in the sublist.
- Python program to sort a List according to the Length of the Elements?
- Sort a list according to the Length of the Elements in Python program
- Python program to sort a list of tuples by second Item
- Python Program to Find the Second Largest Number in a List Using Bubble Sort
- Program to check if we reverse sublist of one list to form second list or not in Python
- Python Pandas - Sort DataFrame in descending order according to the element frequency
- Python Pandas - Sort DataFrame in ascending order according to the element frequency
- Filter tuples according to list element presence in Python
- How to get the second-to-last element of a list in Python?
- Python | Sort the values of first list using second list
- Python program to find the second largest number in a list
- Program to check every sublist in a list containing at least one unique element in Python
- Java Program to Find a Sublist in a List