Program to sort the list elements by second item using Python

by | Jul 12, 2021 | Python Programs

Home » Python » Python Programs » 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.

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

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

Author