Python Program that print elements common at specified index of list elements

PythonServer Side ProgrammingProgramming

When it is required to print the elements common at a specific index in a list of strings, a ‘min’ method, list comprehension and a Boolean flag value can be used.

Example

Below is a demonstration of the same

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']

Explanation

  • A list of strings is defined and is displayed on the console.

  • The list comprehension is used to iterate through elements of the list and get the minimum of lengths of elements.

  • This is assigned to a variable.

  • An empty list is defined.

  • The list is iterated over, and a Boolean value is assigned to 'True'.

  • The elements of the list are iterated again, and if the element at a specific index is not equal to character at a specific index, the Boolean value is assigned to 'False'.

  • The control breaks out of the loop.

  • Depending on this Boolean value, the character is appended to the empty list.

  • This is displayed as output on the console.

raja
Published on 16-Sep-2021 08:44:53
Advertisements