Python program to extract tuples having K digit elements

Here, we have a list of tuples and we need to extract all tuples from the list whose elements are of k digits in Python.
Submitted by Shivang Yadav, on July 31, 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 ordered set of values enclosed in square brackets [].

Example:

list = [3 ,1,  5, 7]

Extracting Tuples having K digit elements

We need to find all the tuples from the list whose all elements have exactly k number of digits.

Input:
[(32, 55), (12, 6), (16, 99), (120, 32)]

Output:
[(32, 55), (16, 99)]

Python programming language provides more than one way to perform the task.

Method 1:

A method to solve the problem is using some built-in function in python to select all tuples with k digit values. We will use the filter() method to filter find all the tuples k digit values, for this we will be using the lambda function.

Program:

# Python Program to extract Tuples having 
# K digit elements

# Initializing list
tupList = [(32, 55), (12, 6), (16, 99), (120, 32)]
print("The List of Tuples :  " + str(tupList))
K = 2

# Updating Values 
updatedTupList = list(filter(lambda sub: all(len(str(ele)) == K for ele in sub), tupList))

# Printing result
print("Extracted List of tuples with k digit elements : " + str(updatedTupList))

Output:

The List of Tuples :  [(32, 55), (12, 6), (16, 99), (120, 32)]
Extracted List of tuples with k digit elements : [(32, 55), (16, 99)]

Method 2:

We can perform the same task in a better way using list comprehension and all() method.

Program:

# Python program to extract Tuples having 
# K digit elements

# Initializing list
tupList = [(32, 55), (12, 6), (16, 99), (120, 32)]
print("The List of Tuples :  " + str(tupList))
K = 2

# Updating Values 
updatedTupList = [tup for tup in tupList if all(len(str(values)) == K for values in tup)]

# Printing result
print("Extracted List of tuples with k digit elements : " + str(updatedTupList))

Output:

The List of Tuples :  [(32, 55), (12, 6), (16, 99), (120, 32)]
Extracted List of tuples with k digit elements : [(32, 55), (16, 99)]

Python Tuple Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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