
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Extract Digits from Tuple List in 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
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.
Advertisements