- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python program to extract only the numbers from a list which have some specific digits
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
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.
Advertisements