Write a Python program to Extract tuples having K digit elements


The program is written in Python and it filters a list of tuples based on the number of digits of the elements in each tuple. Initially, a list val is created containing 5 tuples, each with 2 or 1 elements. The program filters the tuples in the list val using a list comprehension. The list comprehension creates a new list res by iterating over the tuples in val and using the all() function and a generator expression to check if the length of each element in the tuple as a string is equal to a constant K, which is set to 2. If all elements in the tuple meet this condition, the tuple is added to the new list res. Finally, the program prints the original list val and the filtered list res.

Source Code

val = [(47, 23), (3, 78), (22, 53), (121, 45), (7, )]
print("Original List : " ,val)
K = 2
res = [sub for sub in val if all(len(str(ele)) == K for ele in sub)]
 
print("Extracted Tuples : " ,res)

Output

Original List :  [(47, 23), (3, 78), (22, 53), (121, 45), (7,)]
Extracted Tuples :  [(47, 23), (22, 53)]


Example Programs