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
Checking if starting digits are similar in list in Python
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.
Using set() with 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 as no duplicates are allowed.
Example
numbers = [63, 652, 611, 60]
# Given list
print("Given list:", numbers)
# Using set and map
if len(set(x[0] for x in map(str, numbers))) == 1:
print("All elements have same first digit")
else:
print("Not all elements have same first digit")
The output of the above code is ?
Given list: [63, 652, 611, 60] All elements have same first digit
Using all() Function
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
numbers = [63, 652, 611, 70]
# Given list
print("Given list:", numbers)
# Using all() function
if all(str(i)[0] == str(numbers[0])[0] for i in numbers):
print("All elements have same first digit")
else:
print("Not all elements have same first digit")
The output of the above code is ?
Given list: [63, 652, 611, 70] Not all elements have same first digit
Using String Slicing Method
We can also extract the first digit by converting numbers to strings and using slicing to get the first character.
Example
numbers = [123, 145, 167, 189]
# Given list
print("Given list:", numbers)
# Get first digits using string slicing
first_digits = [str(num)[0] for num in numbers]
print("First digits:", first_digits)
# Check if all first digits are same
if len(set(first_digits)) == 1:
print("All elements have same first digit")
else:
print("Not all elements have same first digit")
The output of the above code is ?
Given list: [123, 145, 167, 189] First digits: ['1', '1', '1', '1'] All elements have same first digit
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
set() with map() |
Medium | Good | Compact one-liner solution |
all() function |
High | Best | Early termination on first mismatch |
String slicing |
High | Good | When you need the first digits for other operations |
Conclusion
Use the all() function approach for the most efficient solution as it stops checking once a mismatch is found. The set() method provides a compact one-liner, while string slicing offers the clearest step-by-step approach.
