Python - Check if list contain particular digits

When you need to check if all numbers in a list are composed only of specific digits, you can use string operations and set comparison. This is useful for validating numbers that should only contain certain digits.

Example

Below is a demonstration of checking if list elements contain only particular digits ?

numbers = [415, 133, 145, 451, 154]

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

allowed_digits = [1, 4, 5, 3]

# Convert allowed digits to string set for faster lookup
digit_string = ''.join([str(digit) for digit in allowed_digits])
all_numbers = ''.join([str(num) for num in numbers])

result = True
for char in all_numbers:
    if char not in digit_string:
        result = False
        break

if result:
    print("All elements are made from required digits")
else:
    print("Some elements contain other digits")
The list is:
[415, 133, 145, 451, 154]
All elements are made from required digits

Using Set Operations

A more efficient approach using set operations ?

numbers = [415, 133, 145, 999]
allowed_digits = {1, 4, 5, 3}

print("Numbers:", numbers)
print("Allowed digits:", allowed_digits)

# Check each number individually
for num in numbers:
    num_digits = set(int(digit) for digit in str(num))
    if num_digits.issubset(allowed_digits):
        print(f"{num}: Contains only allowed digits")
    else:
        print(f"{num}: Contains forbidden digits {num_digits - allowed_digits}")
Numbers: [415, 133, 145, 999]
Allowed digits: {1, 3, 4, 5}
415: Contains only allowed digits
133: Contains only allowed digits
145: Contains only allowed digits
999: Contains forbidden digits {9}

Function Approach

Creating a reusable function to check digit constraints ?

def check_digits_only(numbers, allowed_digits):
    """Check if all numbers contain only specified digits"""
    allowed_set = set(str(d) for d in allowed_digits)
    
    for num in numbers:
        num_digits = set(str(num))
        if not num_digits.issubset(allowed_set):
            return False, num
    return True, None

# Test the function
test_numbers = [415, 133, 145, 451, 154]
allowed = [1, 4, 5, 3]

is_valid, invalid_num = check_digits_only(test_numbers, allowed)

if is_valid:
    print("? All numbers contain only allowed digits")
else:
    print(f"? Number {invalid_num} contains forbidden digits")
? All numbers contain only allowed digits

Comparison of Methods

Method Time Complexity Best For
String Join + Loop O(n*m) Simple validation
Set Operations O(n*d) Individual number checking
Function Approach O(n*d) Reusable validation

Conclusion

Use set operations for efficient digit validation. The function approach provides reusability and better error reporting for identifying which numbers contain forbidden digits.

Updated on: 2026-03-26T02:07:07+05:30

434 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements