Python – Find the sum of Length of Strings at given indices

When it is required to find the sum of the length of string at specific indices, the ‘enumerate’ is used to iterate through the elements in the list and adding the length of the element to a list.


Below is a demonstration of the same

my_list = ["python", "is", "best", "for", "coders"]
print("The list is :")

index_list = [0, 1, 4]

result = 0
for index, element in enumerate(my_list):

   if index in index_list:
      result += len(element)

print("The result is :")


The list is :
['python', 'is', 'best', 'for', 'coders']
The result is :


  • A list is defined (which contains strings) and is displayed on the console.

  • Another list with integers is defined.

  • The list of strings is enumerated and iterated over.

  • A variable is assigned to 0.

  • If that index is present in the list of integers, its length is added to the variable.

  • This is the result which is displayed on the console.