Q:

Python program to sort list of tuples alphabetically

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

Sorting List of Tuples Alphabetically

We need to sort all the tuples of the list alphabetically using the first elements of each tuple. To solve will be simply sorting the list taking the first elements of the tuples as a sorting index for the list.

Input:
[("python", 3), ("scala", 7), ("C", 1), ("java", 5)]

output:
[("C", 1), ("java", 5), ("python", 3), ("scala", 7)]

In Python, we can perform the task in multiple ways using one of the multiple methods that are present in the function.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

One method to solve the problem is by using the bubble sort technique. In this technique, we will be accessing the first element of each tuple and sort using a technique similar to bubble sort.

# Initializing and printing list of tuples 
tupleList = [("python", 3), ("scala", 7), ("C", 1), ("java", 5)]
print("The elements of list of tuples are : " + str(tupleList))  

# Sorting list of tuples alphabetically
n = len(tupleList)
for i in range(n):
    for j in range(n-i-1):
        if tupleList[j][0] > tupleList[j + 1][0]:
            tupleList[j], tupleList[j + 1] = tupleList[j + 1], tupleList[j]

# Printing sorted list 
print("The elements of sorted list of tuples are : " + str(tupleList))

Output:

The elements of list of tuples are : [('python', 3), ('scala', 7), ('C', 1), ('java', 5)]
The elements of sorted list of tuples are : [('C', 1), ('java', 5), ('python', 3), ('scala', 7)]

Method 2:

Another method to solve the problem is by using python's built-in sort() method. The method performs in-place sorting of values in Python.

# Program to sort list of tuples alphabetically using bubble sort, 
 
# Initializing and printing list of tuples 
tupleList = [("python", 3), ("scala", 7), ("C", 1), ("java", 5)]
print("The elements of list of tuples are : " + str(tupleList))  

# Sorting list of tuples alphabetically
sortedTupleList = sorted(tupleList, key = lambda x: x[0])

# Printing sorted list 
print("The elements of sorted list of tuples are : " + str(sortedTupleList))

Output:

The elements of list of tuples are : [('python', 3), ('scala', 7), ('C', 1), ('java', 5)]
The elements of sorted list of tuples are : [('C', 1), ('java', 5), ('python', 3), ('scala', 7)]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to find maximum value in record lis... >>
<< Python program to remove nested records from tuple...