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 :") 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)
The list is : ['python', 'is', 'best', 'for', 'coders'] The result is : 14
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.