How To Sort A List Of Tuples In Python

Share This Post

Write a Python program that sorts tuples by the second item of each tuple given a list of them.

Sort A List Of Tuples In Python

Examples:

Nerd, pay attention! The Python Language Basic Training will show you the principles of Python language and enhance your fundamentals.

To start, ensure that you have fully prepared for your encounter. The Python DS Course will make you realize database systems better. To begin your Machine Passion for learning, enroll in the Machine Learning – Basic Level Course.

Using the Bubble Sort

We can execute the sorting using the Bubble Sort approach. Each tuple represents an element in the supplied list. The nested loops are used to access the second element of each tuple. The in-place method of sorting is used here. The time complexity is O(n2), which is similar to the Bubble Sort.

def Sort_Tuple(tup):
	lst = len(tup)
	for i in range(0, lst):
		for j in range(0, lst-i-1):
			if (tup[j][1] > tup[j + 1][1]):
				temp = tup[j]
				tup[j]= tup[j + 1]
				tup[j + 1]= temp


	return tup

tup =[('for', 24), ('is', 10), ('Tuples', 28), ('wholeblogs', 5), ('portal', 20), ('a', 15)]
print(Sort_Tuple(tup))

You can also read further if interested in uninstalling Python On Mac?

Reasons to Sort A List Of Tuples In Python

There are a number of reasons you might want to sort a list of tuples in Python. For example, if you were doing data analysis and wanted to sort the tuples by the second element in each tuple (i.e., the value), this would be a way to do it.

Or if you were working with financial data and wanted to sort the tuples by the first element in each tuple (i.e., the date), this would be a way to do it. Let’s take a look at how to sort a list of tuples in Python.

The first thing we’ll need to do is import the built-in sorting function from the Python standard library.

spot_img

Related Posts

Python for Loop Iteration: How to Easily Manipulate a List

One of the most powerful features of the Python...

How To Get First Characters of a String in Python

Way to find the first characters of a string...

How To Convert Tuple To String In Python

In this post, you will learn how to convert...

How To Convert String to Double in Python

Good to hear, that you want to convert a...

Python TypeError: String Index Out Of Range Solution

A string is an array of characters and part...

How To Remove Empty Strings From a List Of Strings

On this page, we will discuss how to remove...
- Advertisement -spot_img