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
Python program to extract only the numbers from a list which have some specific digits
When you need to extract numbers from a list that contain only specific digits, you can use list comprehension with the all() function. This technique filters numbers by checking if every digit in each number exists in your allowed digits set.
Syntax
result = [num for num in numbers if all(int(digit) in allowed_digits for digit in str(num))]
Example
Let's extract numbers that contain only the digits 2, 3, 4, and 5 ?
numbers = [3345, 2345, 1698, 2475, 1932]
print("The original list is:")
print(numbers)
allowed_digits = [2, 3, 4, 5]
result = [num for num in numbers if all(int(digit) in allowed_digits for digit in str(num))]
print("Numbers containing only digits 2, 3, 4, 5:")
print(result)
The original list is: [3345, 2345, 1698, 2475, 1932] Numbers containing only digits 2, 3, 4, 5: [3345, 2345]
How It Works
The solution works by:
Converting each number to string:
str(num)allows iteration over individual digitsChecking each digit:
int(digit) in allowed_digitsverifies if the digit is allowedUsing all(): Returns
Trueonly if every digit passes the checkList comprehension: Builds the result list with numbers that satisfy the condition
Different Digit Sets
You can use any set of allowed digits ?
numbers = [123, 456, 789, 147, 258, 369]
# Only digits 1, 2, 3
allowed_digits = [1, 2, 3]
result = [num for num in numbers if all(int(digit) in allowed_digits for digit in str(num))]
print("Numbers with only digits 1, 2, 3:")
print(result)
Numbers with only digits 1, 2, 3: [123]
Using Set for Better Performance
For larger digit sets, use a set for faster lookup ?
numbers = [1234, 5678, 9012, 3456, 7890]
allowed_digits = {0, 1, 2, 3, 4, 5, 6} # Using set
result = [num for num in numbers if all(int(digit) in allowed_digits for digit in str(num))]
print("Numbers with only digits 0-6:")
print(result)
Numbers with only digits 0-6: [1234, 3456]
Conclusion
Use list comprehension with all() to filter numbers containing only specific digits. Convert numbers to strings for digit-by-digit checking. Consider using sets for better performance with larger digit collections.
