Checking if starting digits are similar in list in Python

PythonServer Side ProgrammingProgramming

Sometimes in a given Python list we may be interested only in the first digit of each element in the list. In this article we will check if the first digit of all the elements in a list are same or not.

With set and map

Set in Python does not allow any duplicate values in it. So we take the first digit of every element and put it in a set. If all the digits are same then the length of the set will be only 1 has no duplicates allowed.

Example

 Live Demo

Alist = [63,652,611,60]
# Given list
print("Given list : ",Alist)
# Using set and map
if len(set(x[0] for x in map(str, Alist))) == 1:
   print("All elements have same first digit")
else:
   print("Not all elements ,have same first digit")

Output

Running the above code gives us the following result −

Given list : [63, 652, 611, 60]
All elements have same first digit

With all

In this approach we take the first digit of the first element and compare it with the first digit of all the elements. If all of them are equal, then we say all the elements have same first digit.

Example

 Live Demo

Alist = [63,652,611,70]
# Given list
print("Given list : ",Alist)
# Using set and map
if all(str(i)[0] == str(Alist[0])[0] for i in Alist):
   print("All elements have same first digit")
else:
   print("Not all elements ,have same first digit")

Output

Running the above code gives us the following result −

Given list : [63, 652, 611, 70]
Not all elements, have same first digit
raja
Published on 20-May-2020 13:38:40
Advertisements