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
Python Program that print elements common at specified index of list elements
When working with a list of strings, you might need to find characters that appear at the same position across all strings. This can be achieved using list comprehension, the min() function, and a Boolean flag to track common characters.
Example
Below is a demonstration of finding common characters at each index position ?
my_list = ["week", "seek", "beek", "reek", 'meek', 'peek']
print("The list is :")
print(my_list)
min_length = min(len(element) for element in my_list)
my_result = []
for index in range(0, min_length):
flag = True
for element in my_list:
if element[index] != my_list[0][index]:
flag = False
break
if flag:
my_result.append(my_list[0][index])
print("The result is :")
print(my_result)
Output
The list is : ['week', 'seek', 'beek', 'reek', 'meek', 'peek'] The result is : ['e', 'e', 'k']
How It Works
The algorithm follows these steps ?
Find the minimum length among all strings to avoid index errors
Iterate through each character position (index) up to the minimum length
For each position, compare the character in all strings with the character at the same position in the first string
If all characters at that position match, add the character to the result list
Use a Boolean flag to track whether all characters at the current position are identical
Alternative Approach Using all()
Here's a more concise version using the all() function ?
my_list = ["week", "seek", "beek", "reek", 'meek', 'peek']
print("The list is :")
print(my_list)
min_length = min(len(element) for element in my_list)
my_result = []
for index in range(min_length):
if all(element[index] == my_list[0][index] for element in my_list):
my_result.append(my_list[0][index])
print("The result is :")
print(my_result)
The list is : ['week', 'seek', 'beek', 'reek', 'meek', 'peek'] The result is : ['e', 'e', 'k']
Conclusion
This approach efficiently finds common characters at corresponding positions across multiple strings. The min() function ensures we don't exceed the shortest string's length, while the Boolean flag or all() function helps identify matching characters at each index.
