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 −
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)
The list is : [3345, 2345, 1698, 2475, 1932] The result is : [3345, 2345]
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.