Python - Extract Monodigit elements
Last Updated :
30 Apr, 2023
Given List of numbers, extract all numbers with only similar digit.
Input : test_list = [463, 888, 123, 'aaa', 112, 111, 'gfg', 939, 4, 'ccc']
Output : [888, 'aaa', 111, 4, 'ccc']
Explanation : All elements having single unique digit or character.
Input : test_list = [463, "GFG", 8838, 43, 991]
Output : []
Explanation : No element found to be having only single digit.
Method #1 : Using list comprehension + all()
In this, we iterate all the elements using list comprehension, all() is used to check equality of all digits with first digit.
Python3
# Python3 code to demonstrate working of
# Extract Monodigit elements
# Using list comprehension + all()
# initializing list
test_list = [463, 888, 123, "aaa", 112, 111, "gfg", 939, 4, "ccc"]
# printing original lists
print("The original list is : " + str(test_list))
# all() checks for all similar digits
res = [sub for sub in test_list if all(
str(ele) == str(sub)[0] for ele in str(sub))]
# printing result
print("Extracted Numbers : " + str(res))
Output:
The original list is : [463, 888, 123, 'aaa', 112, 111, 'gfg', 939, 4, 'ccc'] Extracted Numbers : [888, 'aaa', 111, 4, 'ccc']
Time complexity: O(n * k), where n is the length of the list and k is the maximum number of digits in a single element of the list.
Auxiliary space: O(n), as we are creating a new list to store the extracted monodigit elements.
Method #2 : Using filter() + lambda + all()
In this, we perform task of filtering using lambda function, filter(), and all() is again used to check equality of all digits.
Python3
# Python3 code to demonstrate working of
# Extract Monodigit elements
# Using filter() + lambda + all()
# initializing list
test_list = [463, 888, 123, "aaa", 112, 111, "gfg", 939, 4, "ccc"]
# printing original lists
print("The original list is : " + str(test_list))
# all() checks for all similar digits
# filter() used for filtering
res = list(filter(lambda sub: all(str(ele) == str(
sub)[0] for ele in str(sub)), test_list))
# printing result
print("Extracted Numbers : " + str(res))
Output:
The original list is : [463, 888, 123, 'aaa', 112, 111, 'gfg', 939, 4, 'ccc'] Extracted Numbers : [888, 'aaa', 111, 4, 'ccc']
Time complexity: O(n * k) where n is the length of the input list and k is the maximum number of digits in a number in the list.
Auxiliary space: O(k) where k is the maximum number of digits in a number in the list, for creating the lambda function.
Method #3 : Using list(),map(),count(),len()
Initially convert every element of list to string.Now iterate over list and iterate over each string in list, check whether the occurrence of first element is equal to length of list.If it is True then the elements of list are having mono digits.
Python3
# Python3 code to demonstrate working of
# Extract Monodigit elements
# initializing list
test_list = [463, 888, 123, "aaa", 112, 111, "gfg", 939, 4, "ccc"]
# printing original lists
print("The original list is : " + str(test_list))
x=list(map(str,test_list))
res=[]
for i in range(0,len(x)):
if(x[i].count(x[i][0])==len(x[i])):
res.append(test_list[i])
# printing result
print("Extracted Numbers : " + str(res))
OutputThe original list is : [463, 888, 123, 'aaa', 112, 111, 'gfg', 939, 4, 'ccc']
Extracted Numbers : [888, 'aaa', 111, 4, 'ccc']
Time complexity: O(n * k) where n is the length of the input list and k is the maximum number of digits in a number in the list.
Auxiliary space: O(k) where k is the maximum number of digits in a number in the list, for creating the lambda function.
Method #4 : Using list(),map(),len() methods and * operator
Python3
# Python3 code to demonstrate working of
# Extract Monodigit elements
# initializing list
test_list = [463, 888, 123, "aaa", 112, 111, "gfg", 939, 4, "ccc"]
# printing original lists
print("The original list is : " + str(test_list))
x=list(map(str,test_list))
res=[]
for i in range(0,len(x)):
a=x[i][0]*len(x[i])
if(a==x[i]):
res.append(test_list[i])
# printing result
print("Extracted Numbers : " + str(res))
OutputThe original list is : [463, 888, 123, 'aaa', 112, 111, 'gfg', 939, 4, 'ccc']
Extracted Numbers : [888, 'aaa', 111, 4, 'ccc']
Method #5 : Using list(),map(),operator.countOf(),len() methods
Python3
# Python3 code to demonstrate working of
# Extract Monodigit elements
# initializing list
test_list = [463, 888, 123, "aaa", 112, 111, "gfg", 939, 4, "ccc"]
# printing original lists
print("The original list is : " + str(test_list))
x=list(map(str,test_list))
res=[]
for i in range(0,len(x)):
import operator
if(operator.countOf(x[i],x[i][0])==len(x[i])):
res.append(test_list[i])
# printing result
print("Extracted Numbers : " + str(res))
OutputThe original list is : [463, 888, 123, 'aaa', 112, 111, 'gfg', 939, 4, 'ccc']
Extracted Numbers : [888, 'aaa', 111, 4, 'ccc']
Time Complexity : O(N)
Auxiliary Space : O(N)
Method #6: Using a for loop and string conversion
We can also solve this problem using a simple for loop and string conversion. We will convert each element of the list to a string and check if all the characters are the same. If they are the same, we will append the element to a new list.
steps
Initialize an empty list to store the extracted elements.
Iterate over each element of the input list using a for loop.
Convert the element to a string using the str() function.
Check if all the characters of the string are the same using the set() function. If the length of the set is 1, it means that all the characters are the same.
If all the characters are the same, append the element to the new list.
Return the new list containing the extracted elements.
Python3
# Python3 code to demonstrate working of
# Extract Monodigit elements
# initializing list
test_list = [463, 888, 123, "aaa", 112, 111, "gfg", 939, 4, "ccc"]
# printing original lists
print("The original list is : " + str(test_list))
# Using for loop and string conversion
res = []
for elem in test_list:
elem_str = str(elem)
if len(set(elem_str)) == 1:
res.append(elem)
# printing result
print("Extracted Numbers : " + str(res))
OutputThe original list is : [463, 888, 123, 'aaa', 112, 111, 'gfg', 939, 4, 'ccc']
Extracted Numbers : [888, 'aaa', 111, 4, 'ccc']
Time complexity: O(n*k), where n is the length of the input list and k is the average length of the elements in the list.
Auxiliary space: O(1), as we are not using any extra space apart from the output list.
Similar Reads
Extract Elements from a Python List
When working with lists in Python, we often need to extract specific elements. The easiest way to extract an element from a list is by using its index. Python uses zero-based indexing, meaning the first element is at index 0. Pythonx = [10, 20, 30, 40, 50] # Extracts the last element a = x[0] print(
2 min read
Python | Extract Strings with only Alphabets
In Python, extracting strings that contain only alphabetic characters involves filtering out any strings that include numbers or special characters. The most efficient way to achieve this is by using the isalpha() method, which checks if all characters in a string are alphabetic.Pythonli= ['gfg', 'i
2 min read
Python - Extract digits from given string
We need to extract the digit from the given string. For example we are given a string s=""abc123def456gh789" we need to extract all the numbers from the string so the output for the given string will become "123456789" In this article we will show different ways to extract digits from a string in Py
2 min read
Python | Get last element of each sublist
Given a list of lists, write a Python program to extract the last element of each sublist in the given list of lists. Examples: Input : [[1, 2, 3], [4, 5], [6, 7, 8, 9]] Output : [3, 5, 9] Input : [['x', 'y', 'z'], ['m'], ['a', 'b'], ['u', 'v']] Output : ['z', 'm', 'b', 'v']  Approach #1 : List co
3 min read
How to get specific elements from list in python
In this article, we will learn how to get specific item(s) from given list. There are multiple methods to achieve this. Most simple method is accessing list item by Index. Pythona = [1, 'geeks', 3, 'for', 5] # accessing specific list item with their indices item1 = a[1] item3 = a[2] item5 = a[4] # n
3 min read
Get first and last elements of a list in Python
The task of getting the first and last elements of a list in Python involves retrieving the initial and final values from a given list. For example, given a list [1, 5, 6, 7, 4], the first element is 1 and the last element is 4, resulting in [1, 4]. Using indexingThis is the most straightforward way
3 min read
Extract substrings between brackets - Python
Extract substrings between bracket means identifying and retrieving portions of text that are enclosed within brackets. This can apply to different types of brackets like (), {}, [] or <>, depending on the context.Using regular expressions Regular expressions are the most efficient way to extr
3 min read
Python | Extract Numbers in Brackets in String
Sometimes, while working with Python strings, we can have a problem in which we have to perform the task of extracting numbers in strings that are enclosed in brackets. Let's discuss the certain ways in which this task can be performed. Method 1: Using regex The way to solve this task is to construc
6 min read
Python | Get first element of each sublist
Given a list of lists, write a Python program to extract first element of each sublist in the given list of lists. Examples: Input : [[1, 2], [3, 4, 5], [6, 7, 8, 9]] Output : [1, 3, 6] Input : [['x', 'y', 'z'], ['m'], ['a', 'b'], ['u', 'v']] Output : ['x', 'm', 'a', 'u'] Â Approach #1 : List compre
3 min read
Python - Extract string between two substrings
The problem is to extract the portion of a string that lies between two specified substrings. For example, in the string "Hello [World]!", if the substrings are "[" and "]", the goal is to extract "World".If the starting or ending substring is missing, handle the case appropriately (e.g., return an
3 min read