5 Best Ways to Extract Specific Digits from Numbers in a Python List

πŸ’‘ Problem Formulation: In Python programming, there may be scenarios where one needs to filter a list of numbers by extracting only those that contain specific digits. For instance, given a list [123, 456, 135, 234] and wanting to extract numbers with the digit 3, the expected output would be [123, 135]. This article provides solutions to this problem using different Python techniques.

Method 1: Using List Comprehension and String Conversion

This method involves converting numbers to strings to check the presence of specific digits using list comprehension. This approach is straightforward and suitable for simple use-cases where performance isn’t a primary concern.

Here’s an example:

numbers = [123, 456, 135, 234]
specific_digits = '3'
filtered_numbers = [num for num in numbers if specific_digits in str(num)]
print(filtered_numbers)

Output: [123, 135]

This code snippet filters the list numbers to include only those values which contain the string '3' anywhere in their digits. List comprehension checks for membership by converting each number to a string and looking for the specific substring.

Method 2: Using Regular Expressions

The re module in Python provides a powerful way to work with regular expressions, which can be used to match patterns in text. In this case, regular expressions are used to check if a number contains specific digits.

Here’s an example:

import re

numbers = [123, 456, 135, 234]
specific_digits = '3'
pattern = re.compile(f'.*{specific_digits}.*')
filtered_numbers = [num for num in numbers if pattern.match(str(num))]
print(filtered_numbers)

Output: [123, 135]

The regular expression pattern is compiled with the chosen specific digit, and each number is checked against this pattern. Numbers which contain the digit are added to the filtered_numbers list.

Method 3: Using a Custom Filter Function

Creating a custom function allows for a more general approach that can be reused for any condition. This method defines a function that checks if the specific digits are in a number and uses this function to filter the list.

Here’s an example:

def contains_specific_digits(number, digits):
    return str(digits) in str(number)

numbers = [123, 456, 135, 234]
specific_digits = 3
filtered_numbers = list(filter(lambda num: contains_specific_digits(num, specific_digits), numbers))
print(filtered_numbers)

Output: [123, 135]

The custom function contains_specific_digits returns a boolean indicating whether a number contains the given digits. The filter function then applies this to each element in the list, and the result is cast to a list.

Method 4: Using itertools.filterfalse Function

The itertools module provides a function filterfalse which, when given a predicate and an iterable, returns those items of iterable for which the predicate is False. This can be inverted to simulate a filtering action where the predicate checks for the absence of specific digits.

Here’s an example:

from itertools import filterfalse

numbers = [123, 456, 135, 234]
specific_digits = '3'
filtered_numbers = list(filterfalse(lambda x: specific_digits not in str(x), numbers))
print(filtered_numbers)

Output: [123, 135]

The lambda function is used as a predicate to return False if the specific digit is not in the number. The filterfalse returns an iterator which is then converted to a list to get the filtered numbers.

Bonus One-Liner Method 5: Using a Functional Approach

Python’s functional programming constructs can also be applied to this problem. Here’s a concise solution using a combination of filter and lambda.

Here’s an example:

numbers = [123, 456, 135, 234]
specific_digits = '3'
filtered_numbers = list(filter(lambda num: specific_digits in str(num), numbers))
print(filtered_numbers)

Output: [123, 135]

This one-liner is a compact version of Method 3. It directly applies the lambda function within the filter call and casts the result to a list to get the numbers containing the specific digit.

Summary/Discussion

  • Method 1: Using List Comprehension and String Conversion. Strengths: Easy to understand, quick to write. Weaknesses: Performance may not be optimal for large lists.
  • Method 2: Using Regular Expressions. Strengths: Very powerful and efficient, particularly for complex patterns. Weaknesses: Can be overkill for simple tasks, readability suffers.
  • Method 3: Custom Filter Function. Strengths: Reusable and clear logic. Weaknesses: Slightly more verbose, could be slower if the custom function is complex.
  • Method 4: Using itertools.filterfalse Function. Strengths: It’s part of the standard itertools module, which is designed for efficient looping. Weaknesses: Somewhat counterintuitive because it filters items that do not match.
  • Bonus Method 5: Functional One-Liner. Strengths: Extremely concise. Weaknesses: May sacrifice readability for brevity.