Python program to extract Mono-digit elements


When it is required to extract mono-digit elements, list comprehension and the ‘all operator are used.

Below is a demonstration of the same −

Example

my_list = [863, 1, 463, "pyt", 782, 241, "is", 639, 4, "fun"]

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

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

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

Output

The list is :
[863, 1, 463, 'pyt', 782, 241, 'is', 639, 4, 'fun']
The result is :
[1, 4]

Explanation

  • A list is defined and displayed on the console.

  • A list comprehension is used to iterate over the list, and every element is converted to a list and compared with the zeroth element.

  • This is converted to a list.

  • This is assigned to a variable.

  • This is the output that is displayed on the console.

Updated on: 08-Sep-2021

140 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements