Skip to content
Home » How To Sort A List Of Tuples In Python

How To Sort A List Of Tuples In Python

  • by
String Index Out Of Range Solution

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.

Tags:

Leave a Reply

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