Program to sort the list elements by second item using Python

Introduction

The task is to sort the given list of elements by second item. In this article we will discuss different ways of sorting in python.

Program to sort the list elements by second item using Python

Program

Approach 1: sort() method

Program to sort the list elements by second item using Python Approach 1

Output:

Program to sort the list elements by second item using Python Output

Approach 2: sorted() method

Program to sort the list elements by second item using Python Approach 2

Output:

Program to sort the list elements by second item using Python Output 2

Approach 3: bubble sort

Program to sort the list elements by second item using Python Approach 3

Output:

Program to sort the list elements by second item using Python Output 3

Explanation

We have used three approaches to sort the elements by second element. The first approach is using sort() method. Python provides the in-built function sort() to sort the elements of list. When we use this method, the actual list values are changed and get sorted.

The second approach is using python in-built sorted() method. This method does not change the original list, instead just returns the sorted value.

The third and last approach is using bubble sort algorithm. From code we can see that the second value of list is passed in for loop and sorted accordingly.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.