Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to extract Mono-digit elements
When it is required to extract mono-digit elements (numbers where all digits are the same), list comprehension and the all operator are used.
What are Mono-digit Elements?
Mono-digit elements are numbers where all digits are identical, such as 1, 22, 333, 4444, etc. For single-digit numbers, they are naturally mono-digit.
Example
my_list = [863, 1, 463, "pyt", 782, 241, "is", 639, 4, "fun", 22, 333]
print("The list is :")
print(my_list)
my_result = [item for item in my_list if isinstance(item, int) and all(str(digit) == str(item)[0] for digit in str(item))]
print("The result is :")
print(my_result)
Output
The list is : [863, 1, 463, 'pyt', 782, 241, 'is', 639, 4, 'fun', 22, 333] The result is : [1, 4, 22, 333]
How It Works
The list comprehension performs the following steps:
isinstance(item, int)? Filters only integer values from the liststr(item)[0]? Gets the first digit of the number as a stringall(str(digit) == str(item)[0] for digit in str(item))? Checks if all digits match the first digitReturns only numbers where all digits are identical
Alternative Approach Using Function
def extract_mono_digit_elements(data):
mono_digits = []
for item in data:
if isinstance(item, int):
str_item = str(item)
if len(set(str_item)) == 1: # All digits are same
mono_digits.append(item)
return mono_digits
my_list = [863, 1, 463, 782, 241, 639, 4, 22, 333, 5555]
result = extract_mono_digit_elements(my_list)
print("Original list:", my_list)
print("Mono-digit elements:", result)
Original list: [863, 1, 463, 782, 241, 639, 4, 22, 333, 5555] Mono-digit elements: [1, 4, 22, 333, 5555]
Conclusion
Use list comprehension with all() to extract mono-digit elements efficiently. The isinstance() check ensures only integers are processed, while all() verifies all digits are identical.
