Extract tuples having K digit elements in Python


When it is required to extract tuples that have a specific number of elements, list comprehension can be used. It iterates over the elements of the list of tuple and puts forth condition that needs to be fulfilled. This will filter out the specific elements and stores them in another variable.

Below is a demonstration of the same −

Example

 Live Demo

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 tostr(K)
The tuples extracted are :
[(34, 56), (11, 35), (78,)]

Explanation

  • A list of the tuple is defined and is displayed on the console.

  • A value for ‘K’ is initialized.

  • List comprehension is used to iterate over the list of the tuple.

  • It is checked to see all the tuples in the list have the same size.

  • It is converted to a list, and is assigned to a variable.

  • It is displayed as output on the console.

Updated on: 14-Apr-2021

235 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements