Python program to extract only the numbers from a list which have some specific digits

PythonServer Side ProgrammingProgramming

When it is required to extract only the numbers from a list which have some specific digits, a list comprehension and the ‘all’ operator is used.

Below is a demonstration of the same −

Example

 Live Demo

my_list = [3345, 2345, 1698, 2475, 1932]

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

digit_list = [2, 3, 5, 4]

my_result = [index for index in my_list if all(int(element) in digit_list for element in str(index))]

print("The result is :")
print(my_result)

Output

The list is :
[3345, 2345, 1698, 2475, 1932]
The result is :
[3345, 2345]

Explanation

  • A list is defined and is displayed on the console.

  • Another list of integers is defined.

  • The list comprehension is used to iterate over the elements, and the elements are converted to string if they are of integer type.

  • This is done if all elements are integer type.

  • It is converted to a list and assigned to a variable.

  • This is displayed as output on the console.

raja
Published on 06-Sep-2021 07:19:50
Advertisements