
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the Sum of Length of Strings at Given Indices in Python
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.
Advertisements