Open In App

Python program to sort a list of tuples alphabetically

Last Updated : 25 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a list of tuples, write a Python program to sort the tuples alphabetically by the first item of each tuple. Examples:

Input: [("Amana", 28), ("Zenat", 30), ("Abhishek", 29), ("Nikhil", 21), ("B", "C")]
Output: [('Amana', 28), ('Abhishek', 29), ('B', 'C'), ('Nikhil', 21), ('Zenat', 30)]

Input: [("aaaa", 28), ("aa", 30), ("bab", 29), ("bb", 21), ("csa", "C")]
Output: [('aa', 30), ('aaaa', 28), ('bab', 29), ('bb', 21), ('csa', 'C')]

Method 1: Using Bubble sort Using the technique of Bubble Sort to we can perform the sorting. Note that each tuple is an element in the given list. Access the first element of each tuple using the nested loops. This performs the in-place method of sorting. The time complexity is similar to the Bubble Sort i.e. O(n^2). 

Python3




# Python program to sort a
# list of tuples alphabetically
 
 
# Function to sort the list of
# tuples
 
def SortTuple(tup):
     
    # Getting the length of list
    # of tuples
    n = len(tup)
     
    for i in range(n):
        for j in range(n-i-1):
             
            if tup[j][0] > tup[j + 1][0]:
                tup[j], tup[j + 1] = tup[j + 1], tup[j]
                 
    return tup
     
# Driver's code
 
tup = [("Amana", 28), ("Zenat", 30), ("Abhishek", 29),
        ("Nikhil", 21), ("B", "C")]
         
print(SortTuple(tup))


Output:

[('Abhishek', 29), ('Amana', 28), ('B', 'C'), ('Nikhil', 21), ('Zenat', 30)]

Method 2: Using sort() method While sorting via this method the actual content of the tuple is changed, and just like the previous method, the in-place method of the sort is performed. 

Python3




# Python program to sort a list of
# tuples using sort() 
   
# Function to sort the list
def SortTuple(tup): 
   
    # reverse = None (Sorts in Ascending order) 
    # key is set to sort using first element of 
    # sublist lambda has been used 
    tup.sort(key = lambda x: x[0]) 
    return tup 
     
# Driver's code
 
tup = [("Amana", 28), ("Zenat", 30), ("Abhishek", 29),
        ("Nikhil", 21), ("B", "C")]
         
print(SortTuple(tup))


Output:

[('Abhishek', 29), ('Amana', 28), ('B', 'C'), ('Nikhil', 21), ('Zenat', 30)]

Method 3: Using sorted() method sorted() method is a method of list class that returns the sorted list without making any changes to the original list. 

Python3




# Python program to sort a list of
# tuples using sorted() 
   
# Function to sort the list
def Sort_Tuple(tup): 
   
    # reverse = None (Sorts in Ascending order) 
    # key is set to sort using first element of 
    # sublist lambda has been used 
    return(sorted(tup, key = lambda x: x[0]))  
   
# Driver Code 
tup = [("Amana", 28), ("Zenat", 30), ("Abhishek", 29),
        ("Nikhil", 21), ("B", "C")]
   
# printing the sorted list of tuples
print(Sort_Tuple(tup))


Output:

[('Abhishek', 29), ('Amana', 28), ('B', 'C'), ('Nikhil', 21), ('Zenat', 30)]

Time Complexity: O(n*logn), as sorted() function is used.
Auxiliary Space: O(n), where n is length of list.



Similar Reads

Python | Sort the list alphabetically in a dictionary
In Python Dictionary is quite a useful data structure, which is usually used to hash a particular key with value, so that they can be retrieved efficiently. Let's see how to sort the list alphabetically in a dictionary. Sort a List Alphabetically in PythonIn Python, Sorting a List Alphabetically is a typical activity that takes on added interest wh
3 min read
How To Sort List Of Strings In Alphabetically
When working with Python programs, be it any machine learning program or simple text processing program, you might have come across a need to sort a list of strings alphabetically, either in ascending or reverse order. Strings are sorted alphabetically based on their initial letter (a-z or A-Z). But, the strings that start with uppercase characters
3 min read
Python | Ways to sort letters of string alphabetically
Given a string of letters, write a python program to sort the given string in an alphabetical order. Example: Input : PYTHON Output : HNOPTY Input : Geeks Output : eeGksNaive Method to sort letters of string alphabetically Here we are converting the string into list and then finally sorting the entire list alphabet wise. C/C++ Code s ="GEEKSFO
2 min read
Python | Sort the items alphabetically from given dictionary
Given a dictionary, write a Python program to get the alphabetically sorted items from given dictionary and print it. Let’s see some ways we can do this task. Code #1: Using dict.items() C/C++ Code # Python program to sort the items alphabetically from given dictionary # initialising _dictionary dict = {'key2' : 'For', 'key3': 'IsGeeks', 'key1' : '
1 min read
Python program to find Tuples with positive elements in List of tuples
Given a list of tuples. The task is to get all the tuples that have all positive elements. Examples: Input : test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, -6)] Output : [(4, 5, 9)] Explanation : Extracted tuples with all positive elements. Input : test_list = [(-4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, -6)] Output : [] Explanation : No tuple wit
10 min read
Python program to find tuples which have all elements divisible by K from a list of tuples
Given a list of tuples. The task is to extract all tuples which have all elements divisible by K. Input : test_list = [(6, 24, 12), (60, 12, 6), (12, 18, 21)], K = 6 Output : [(6, 24, 12), (60, 12, 6)] Explanation : Both tuples have all elements multiple of 6. Input : test_list = [(6, 24, 12), (60, 10, 5), (12, 18, 21)], K = 5 Output : [(60, 10, 5)
7 min read
Python | Remove duplicate tuples from list of tuples
Given a list of tuples, Write a Python program to remove all the duplicated tuples from the given list. Examples: Input : [(1, 2), (5, 7), (3, 6), (1, 2)] Output : [(1, 2), (5, 7), (3, 6)] Input : [('a', 'z'), ('a', 'x'), ('z', 'x'), ('a', 'x'), ('z', 'x')] Output : [('a', 'z'), ('a', 'x'), ('z', 'x')] Method #1 : List comprehension This is a naive
5 min read
Python | Find the tuples containing the given element from a list of tuples
Given a list of tuples, the task is to find all those tuples containing the given element, say n. Examples: Input: n = 11, list = [(11, 22), (33, 55), (55, 77), (11, 44)] Output: [(11, 22), (11, 44)] Input: n = 3, list = [(14, 3),(23, 41),(33, 62),(1, 3),(3, 3)] Output: [(14, 3), (1, 3), (3, 3)] There are multiple ways we can find the tuples contai
6 min read
Python | Remove tuples from list of tuples if greater than n
Given a list of a tuple, the task is to remove all the tuples from list, if it's greater than n (say 100). Let's discuss a few methods for the same. Method #1: Using lambda STEPS: Initialize a list of tuples: ini_tuple = [('b', 100), ('c', 200), ('c', 45), ('d', 876), ('e', 75)]Print the initial list: print("intial_list", str(ini_tuple))Define the
6 min read
Python | Remove tuples having duplicate first value from given list of tuples
Given a list of tuples, the task is to remove all tuples having duplicate first values from the given list of tuples. Examples: Input: [(12.121, 'Tuple1'), (12.121, 'Tuple2'), (12.121, 'Tuple3'), (923232.2323, 'Tuple4')] Output: [(12.121, 'Tuple1'), (923232.2323, 'Tuple4')]Input: [('Tuple1', 121), ('Tuple2', 125), ('Tuple1', 135), ('Tuple4', 478)]
7 min read