Extract tuples having K digit elements in Python

When working with lists of tuples, you may need to extract tuples containing elements with a specific number of digits. This can be accomplished using list comprehension with the all() function and len() to check digit counts.

Example

Here's how to extract tuples where all elements have exactly K digits ?

my_list = [(34, 56), (45, 6), (111, 90), (11, 35), (78, )]

print("The list is :")
print(my_list)

K = 2
print("The value of K has been initialized to", str(K))

my_result = [sub for sub in my_list if all(len(str(elem)) == K for elem in sub)]

print("The tuples extracted are :")
print(my_result)

Output

The list is :
[(34, 56), (45, 6), (111, 90), (11, 35), (78,)]
The value of K has been initialized to 2
The tuples extracted are :
[(34, 56), (11, 35)]

How It Works

The solution uses list comprehension with these key components ?

  • List comprehension: [sub for sub in my_list if condition] iterates through each tuple
  • all() function: Returns True only if all elements in the tuple meet the condition
  • len(str(elem)): Converts each element to string and counts its digits
  • Condition: len(str(elem)) == K checks if the element has exactly K digits

Different Values of K

Let's test with different digit counts ?

my_list = [(34, 56), (45, 6), (111, 90), (11, 35), (78, )]

# Extract tuples with 1-digit elements
K = 1
result_1 = [sub for sub in my_list if all(len(str(elem)) == K for elem in sub)]
print(f"Tuples with {K}-digit elements: {result_1}")

# Extract tuples with 3-digit elements  
K = 3
result_3 = [sub for sub in my_list if all(len(str(elem)) == K for elem in sub)]
print(f"Tuples with {K}-digit elements: {result_3}")
Tuples with 1-digit elements: [(45, 6)]
Tuples with 3-digit elements: []

Alternative Using Filter

You can also use the filter() function for the same result ?

my_list = [(34, 56), (45, 6), (111, 90), (11, 35), (78, )]
K = 2

def has_k_digits(tuple_item):
    return all(len(str(elem)) == K for elem in tuple_item)

my_result = list(filter(has_k_digits, my_list))
print("Tuples extracted using filter():", my_result)
Tuples extracted using filter(): [(34, 56), (11, 35)]

Conclusion

Use list comprehension with all() and len(str()) to extract tuples containing elements with exactly K digits. This approach efficiently filters tuples based on digit count criteria.

Updated on: 2026-03-25T18:34:26+05:30

531 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements