Sort sublist Python

This is a Python Program to sort the list according to the second element in the sublist.

Problem Description

The program takes a list of lists and sorts the list according to the second element in the sublist.

Problem Solution

1. Take in a list containing sublists.
2. Using two for loops, use bubble sort to sort the sublists based on the second value of the sublist.
3. If the second element of the first sublist is greater than the second element of the second sublist, exchange the entire sublist.
4. Print the sorted list.
5. Exit.

advertisement
Program/Source Code

Here is source code of the Python Program to sort the list according to the second element in the sublist. The program output is also shown below.

a=[['A',34],['B',21],['C',26]] for i in range[0,len[a]]: for j in range[0,len[a]-i-1]: if[a[j][1]>a[j+1][1]]: temp=a[j] a[j]=a[j+1] a[j+1]=temp print[a]
Program Explanation

1. User must enter a list containing several sublists.
2. Then bubble sort is implemented to sort the list according to the second element in the sublist.
3. If the second element of the first sublist is greater than the second element of the second sublist, then the entire sublist is switched.
4. This process continues till the entire list has been sorted.
5. The sorted list is then printed.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
Runtime Test Cases
Case 1: [['B', 21], ['C', 26], ['A', 34]]

Sanfoundry Global Education & Learning Series Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

Check this: Python Books | Information Technology Books
advertisement
« Prev - Python Program to Find the Sum of the Series: 1 + 1/2 + 1/3 + .. + 1/N
» Next - Python Program to Merge Two Lists and Sort it
Next Steps:

  • Get Free Certificate of Merit in Python Programming
  • Participate in Python Programming Certification Contest
  • Become a Top Ranker in Python Programming
  • Take Python Programming Tests
  • Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
  • Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:

  • Practice Programming MCQs
  • Buy Python Books
  • Apply for Programming Internship
  • Buy Information Technology Books
  • Apply for Python Internship

Video liên quan

Chủ Đề