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.

Example

Below is a demonstration of the same

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

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 :")
print(result)

Output

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

Explanation

  • 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.

Updated on: 20-Sep-2021

211 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements