Python - List Elements with given digit

Python - List Elements with given digit

Let's create a tutorial on how to filter list elements containing a specific digit.

1. Introduction:

Given a list of numbers, the aim is to retrieve elements that contain a specific digit. For example, if you're given the list [123, 456, 789, 120] and the digit 1, the resulting list should be [123, 120].

2. Using List Comprehension:

One of the simplest ways to achieve this is by using list comprehension.

def filter_by_digit(numbers, digit): return [num for num in numbers if str(digit) in str(num)] data = [123, 456, 789, 120] filtered_numbers = filter_by_digit(data, 1) print(filtered_numbers) # Output: [123, 120] 

3. Using the filter() Function:

The built-in filter() function can be used in combination with a lambda function to achieve the same result.

def has_digit(num, digit): return str(digit) in str(num) data = [123, 456, 789, 120] filtered_numbers = list(filter(lambda x: has_digit(x, 1), data)) print(filtered_numbers) # Output: [123, 120] 

4. Real-world Scenario:

Imagine you're working with a database of phone numbers, and you want to find all numbers that have the digit 8 in the area code. Using the methods above, you can easily filter out the numbers that meet the criteria.

5. Variations:

  1. Multiple Digits: Extend the function to filter numbers that contain any digit from a given list of digits.
  2. Exclusion: Modify the function to exclude numbers that contain a specific digit.

6. Conclusion:

Filtering list elements based on the presence of a specific digit can be effectively accomplished using Python's list comprehensions or the filter() function. These techniques are flexible and can be adapted to a variety of scenarios involving list filtering and data extraction.


More Tags

angular9 apache-modules dfsort json-serialization azure-powershell uninstallation haversine gradle-tooling-api browser-detection bottomnavigationview

More Programming Guides

Other Guides

More Programming Examples