Extract digits from Tuple list Python


When it is required to extract digits from a list of tuple, list comprehension can be used.

Below is the demonstration of the same −

Example

 Live Demo

my_list = [(67, 2), (34, 65), (212, 23), (17, 67), (18, )]

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

N = 2
print("The value of N is ")
print(N)
my_result = [sub for sub in my_list if all(len(str(ele)) == N for ele in sub)]

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

Output

The list is :
[(67, 2), (34, 65), (212, 23), (17, 67), (18,)]
The value of N is
2
The extracted tuples are :
[(34, 65), (17, 67), (18,)]

Explanation

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

  • The value of N is initialized to 2.

  • This is displayed on the console.

  • The list comprehension is used to iterate through the list and check if length of all the elements in the list of tuple are equal to a specific value.

  • If they are equal to a specific value, it is assigned to a variable.

  • This variable is displayed as output on the console.

Updated on: 17-Apr-2021

425 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements