Python program to sort tuples by total digits

Here, we have a list of tuples and we need to sort the tuples of the list based on the total number of digits present in the tuple using Python program.
Submitted by Shivang Yadav, on September 16, 2021

Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.

Tuples in Python is a collection of items similar to list with the difference that it is ordered and immutable.

Example:

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

List is a sequence data type. It is mutable as its values in the list can be modified. It is a collection of an ordered set of values enclosed in square brackets [].

list = [3 ,1,  5, 7]

List of tuples is a list whose each element is a tuple.

tupList = [("python", 7), ("learn" , 1), ("programming", 7), ("code" , 3)]

Sorting Tuples by Total Digits

We have a list of tuples with multiple values. And we need to sort the tuples of the list by the total number of digits in the tuple.

Input:
[(2, 4), (12, 40), (1, 23), (43343, 1)]

Output:
[(2, 4), (1, 23), (12, 40), (43343, 1)]

Method 1:

A method to solve the problem is by sorting the list using the sort() method with the sorting key is the sum of lengths of all elements of the tuple.

# Python program to sort tuples 
# by total number of digits in list of tuples 

def digCount(tup):
	return sum([len(str(val)) for val in tup ])

# Creating and Printing tuple list 
tupList = [(43343, 1), (2, 4), (12, 40), (1, 23)]
print("unsorted Tuple list : " + str(tupList))

# sorting list based on digit count using digCount method  
tupList.sort(key = digCount)

# printing result
print("sorted Tuple list : " + str(tupList))

Output:

unsorted Tuple list : [(43343, 1), (2, 4), (12, 40), (1, 23)]
sorted Tuple list : [(2, 4), (1, 23), (12, 40), (43343, 1)]

Method 2:

One method to perform the task is using the lambda function instead of passing a method to the tuple. The lambda will take the list and sort it based on the count of digits in the tuple.

# Python program to sort tuples 
# by total number of digits in list of tuples 

# Creating and Printing tuple list 
tupList = [(43343, 1), (2, 4), (12, 40), (1, 23)]
print("Unsorted Tuple list : " + str(tupList))

# sorting list based on digit count using digCount method  
digitSortedTuple = sorted(tupList, key = lambda tup : sum([len(str(vals)) for vals in tup ]))

# printing result
print("Sorted Tuple list : " + str(digitSortedTuple))

Output:

Unsorted Tuple list : [(43343, 1), (2, 4), (12, 40), (1, 23)]
Sorted Tuple list : [(2, 4), (1, 23), (12, 40), (43343, 1)]

Python Tuple Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.