Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Extract digits from Tuple list Python
When working with tuple lists in Python, you might need to extract tuples where all elements have a specific number of digits. This can be achieved using list comprehension with the all() function and string length checking.
Syntax
result = [tuple for tuple in tuple_list if all(len(str(element)) == N for element in tuple)]
Example
Let's extract tuples where all elements have exactly 2 digits ?
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)
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)]
How It Works
The solution uses several Python concepts:
List Comprehension: Iterates through each tuple in the list
all() Function: Returns True only if all elements in the tuple meet the condition
str() Conversion: Converts numbers to strings to count digits using
len()Length Check:
len(str(ele)) == Nchecks if each element has exactly N digits
Different Digit Lengths
Here's an example extracting tuples with 3−digit numbers ?
my_list = [(123, 456), (78, 90), (100, 999), (12, 345)]
N = 3
result = [sub for sub in my_list if all(len(str(ele)) == N for ele in sub)]
print("Tuples with 3-digit numbers:")
print(result)
Tuples with 3-digit numbers: [(123, 456), (100, 999)]
Handling Edge Cases
The method works with single−element tuples and handles negative numbers ?
my_list = [(12, -34), (123,), (-99, 88), (5, 67)]
N = 2
result = [sub for sub in my_list if all(len(str(abs(ele))) == N for ele in sub)]
print("Tuples with 2-digit numbers (ignoring sign):")
print(result)
Tuples with 2-digit numbers (ignoring sign): [(12, -34), (-99, 88)]
Conclusion
Use list comprehension with all() and len(str()) to extract tuples where all elements have a specific number of digits. This approach is efficient and handles various tuple sizes and negative numbers when combined with abs().
