Python | Checking if starting digits are similar in list
Last Updated :
09 Apr, 2023
Sometimes we may face a problem in which we need to find a list if it contains numbers with the same digits. This particular utility has an application in day-day programming. Let's discuss certain ways in which this task can be achieved.
Method #1: Using list comprehension + map()
We can approach this problem by converting the elements to the strings and then testing the starting element of string and if they are equal we can return true and then convert to set and test for size of result to be one. The conversion is done by map, set function converts to set and list comprehension checks for first element of string.
Python3
# Python3 code to demonstrate
# checking for first digit in elements
# using list comprehension + map()
# initializing list
test_list = [45, 4, 428829, 432]
# printing original list
print("The original list : " + str(test_list))
# using list comprehension + map()
# checking for first digit in elements
res = len(set(sub[0] for sub in map(str, test_list))) == 1
# print result
print("Does each element start with same digit ? " + str(res))
OutputThe original list : [45, 4, 428829, 432]
Does each element start with same digit ? True
Time Complexity: O(n) where n is the number of elements in the list.
Auxiliary Space: O(n) as we are storing the first digit of each element in a set.
Method #2: Using all() + list comprehension
This is yet another approach in which this problem can be solved. In this, we use all function to check for all elements and return a Boolean result and list comprehension does the part of the conversion of string by str function and checking for all elements with the first digit of first element.
Python3
# Python3 code to demonstrate
# checking for first digit in elements
# using all() + list comprehension
# initializing list
test_list = [45, 4, 428829, 432]
# printing original list
print("The original list : " + str(test_list))
# using all() + list comprehension
# checking for first digit in elements
res = all(str(i)[0] == str(test_list[0])[0] for i in test_list)
# print result
print("Does each element start with same digit ? " + str(res))
OutputThe original list : [45, 4, 428829, 432]
Does each element start with same digit ? True
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(1), as the space used is constant regardless of the input size.
Method #3: Using startswith() method
Python3
# Python3 code to demonstrate
# checking for first digit in elements
# initializing list
test_list = [45, 4, 428829, 432]
p=list(map(str,test_list))
# printing original list
print("The original list : " + str(test_list))
c=0
x=p[0][0]
for i in p:
if(i.startswith(x)):
c+=1
res=False
if(c==len(p)):
res=True
# print result
print("Does each element start with same digit ? " + str(res))
OutputThe original list : [45, 4, 428829, 432]
Does each element start with same digit ? True
Time complexity: O(n) - The code iterates through each element of the list once.
Auxiliary space: O(n) - The code creates a new list 'p' with the same number of elements as the original list.
Method #4 : Using for loop,len() method
Python3
# Python3 code to demonstrate
# checking for first digit in elements
# initializing list
test_list = [45, 4, 428829, 432]
p = list(map(str, test_list))
# printing original list
print("The original list : " + str(test_list))
c = 0
x = [p[0][0]]*len(test_list)
y = []
for i in p:
y.append(i[0])
res = False
if(x == y):
res = True
# print result
print("Does each element start with same digit ? " + str(res))
OutputThe original list : [45, 4, 428829, 432]
Does each element start with same digit ? True
Method #5 : Using re
The code initializes a list test_list with four elements. Then it prints the original list to the console.
Next, it uses a list comprehension to extract the first digit from each element in the test_list. It does this by using the findall() function from the re module to match a single digit in the string representation of each element, and then it gets the first element from the resulting list. The resulting list is stored in the first_digits variable.
Finally, it uses the len() and set() functions to check if all the elements in the first_digits list are the same. It does this by converting the first_digits list to a set, which removes any duplicates, and then checking if the length of the set is equal to 1. The result is stored in the res variable, which is a Boolean value indicating whether all the elements in the first_digits list are the same. The result is printed to the console.
Here is an example of how this can be implemented:
Python3
import re
# initializing list
test_list = [45, 4, 428829, 432]
# printing original list
print("The original list:", test_list)
# extracting digits from elements
first_digits = [re.findall(r'\d', str(i))[0] for i in test_list]
# checking if all digits are the same
res = len(set(first_digits)) == 1
# print result
print("Does each element contain the same digits?", res)
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original list: [45, 4, 428829, 432]
Does each element contain the same digits? True
Time complexity: O(n), where n is the length of the test_list, because the list comprehension iterates over the elements of the test_list once, and the len() and set() functions each iterate over the elements of the first_digits list once.
Auxiliary space: O(n), because the first_digits list grows by one element for each iteration of the list comprehension, and the set() function creates a new set object with a capacity equal to the number of elements in the first_digits list.
Method #6 : Using str() and count() methods
- Initiated a for loop to traverse the list
- Converted element to string and appended the first character to a list
- Checked if the count of first element of list to length of list(using count())
- If True assign True to res variable
- Display res variable
Python3
# Python3 code to demonstrate
# checking for first digit in elements
# initializing list
test_list = [45, 4, 428829, 432]
# printing original list
print("The original list : " + str(test_list))
# checking for first digit in elements
res=False
y=[]
for i in test_list:
x=str(i)
y.append(x[0])
if(y.count(y[0])==len(y)):
res=True
# print result
print("Does each element start with same digit ? " + str(res))
OutputThe original list : [45, 4, 428829, 432]
Does each element start with same digit ? True
Time Complexity : O(N)
Auxiliary Space : O(1)
Method #7: Using set comprehension and string slicing
This method uses a set comprehension to extract the first digit of each element in the list and stores them in a set. Then it checks whether the length of the set is equal to 1, which means all elements have the same first digit.
Python3
# initializing list
test_list = [45, 4, 428829, 432]
# printing original list
print("The original list : " + str(test_list))
# checking for first digit in elements
first_digits = {str(i)[0] for i in test_list}
res = len(first_digits) == 1
# print result
print("Does each element start with same digit? " + str(res))
OutputThe original list : [45, 4, 428829, 432]
Does each element start with same digit? True
Time complexity: O(n), where n is the number of elements in the list.
Auxiliary space: O(n), since we need to store the first digit of each element in a set.
Method #8: Using a while loop and integer division
Algorithm:
- Initialize a variable 'first_digit' with the first digit of the first element in the list.
- Use a while loop to iterate through the remaining elements of the list and for each element, get its first digit by dividing it by 10 until the quotient is less than 10.
- Check if the first digit is equal to 'first_digit'. If not, return False.
- If the loop completes without returning False, return True.
Implementation:
Python3
# Initialize the list
test_list = [45, 4, 428829, 432]
# Print original list
print("The original list : " + str(test_list))
# Check for first digit in elements
first_digit = test_list[0] // 10**(len(str(test_list[0]))-1)
for i in range(1, len(test_list)):
num = test_list[i]
while num >= 10:
num //= 10
if num != first_digit:
res = False
break
else:
res = True
# Print result
print("Does each element start with same digit? " + str(res))
OutputThe original list : [45, 4, 428829, 432]
Does each element start with same digit? True
Time Complexity: O(n*m), where n is the length of the list and m is the number of digits in the largest element.
Auxiliary Space: O(1)
Similar Reads
Python | Grouping similar substrings in list
Sometimes we have an application in which we require to group common prefix strings into one such that further processing can be done according to the grouping. This type of grouping is useful in the cases of Machine Learning and Web Development. Let's discuss certain ways in which this can be done.
7 min read
Python - Check if string starts with any element in list
We need to check if a given string starts with any element from a list of substrings. Let's discuss different methods to solve this problem.Using startswith() with tuplestartswith() method in Python can accept a tuple of strings to check if the string starts with any of them. This is one of the most
3 min read
Python - Check if all elements in List are same
To check if all items in list are same, we have multiple methods available in Python. Using SetUsing set() is the best method to check if all items are same in list. Pythona = [3, 3, 3, 3] # Check if all elements are the same result = len(set(a)) == 1 print(result) OutputTrue Explanation:Converting
3 min read
Python - Test if Kth character is digit in String
Given a String, check if Kth index is a digit. Input : test_str = 'geeks9geeks', K = 5 Output : True Explanation : 5th idx element is 9, a digit, hence True.Input : test_str = 'geeks9geeks', K = 4 Output : False Explanation : 4th idx element is s, not a digit, hence False. Method #1: Using in operat
5 min read
Python | Split strings and digits from string list
Sometimes, while working with String list, we can have a problem in which we need to remove the surrounding stray characters or noise from list of digits. This can be in form of Currency prefix, signs of numbers etc. Let's discuss a way in which this task can be performed. Method #1 : Using list com
5 min read
Python - Check if List contains elements in Range
Checking if a list contains elements within a specific range is a common problem. In this article, we will various approaches to test if elements of a list fall within a given range in Python. Let's start with a simple method to Test whether a list contains elements in a range.Using any() Function -
3 min read
Python | Kth index character similar Strings
Sometimes, we require to get the words that have the Kth index with the specific letter. This kind of use case is quiet common in places of common programming projects or competitive programming. Letâs discuss certain shorthand to deal with this problem in Python. Method #1: Using list comprehension
3 min read
Python - Check if list contain particular digits
Given a List and some digits, the task is to write a python program to check if the list contains only certain digits. Input : test_list = [435, 133, 113, 451, 134], digs = [1, 4, 5, 3] Output : True Explanation : All elements are made out of 1, 4, 5 or 3 only.Input : test_list = [435, 133, 113, 451
14 min read
Python - First K consecutive digits in String
Given a String and number K, extract first K consecutive digits making number. Input : test_str = "geeks5geeks43best", K = 2 Output : 43 Explanation : 43 is first 2 consecutive digits. Input : test_str = "geeks5gee2ks439best", K = 3 Output : 439 Explanation : 439 is first 3 consecutive digits. Metho
5 min read
Check for Sublist in List-Python
The task of checking for a sublist in a list in Python involves determining whether a given sequence of elements (sublist) appears consecutively within a larger list. This is a common problem in programming, particularly in data processing and pattern matching. For example, if we have a list [5, 6,
4 min read