Q:

Python program to extract tuples having K digit elements

belongs to collection: Python Tuple Programs

0

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.

All Answers

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

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)]

 

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 tuples from list which have... >>
<< Python program to convert set into tuple and tuple...