Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Find the sum of Length of Strings at given indices
When it is required to find the sum of the length of strings at specific indices, we can use various approaches. The enumerate function helps iterate through elements with their indices, allowing us to check if an index matches our target indices.
Method 1: Using enumerate()
This approach iterates through the list with indices and checks if each index is in our target list ?
my_list = ["python", "is", "best", "for", "coders"]
print("The list is :")
print(my_list)
index_list = [0, 1, 4]
print("Target indices:", index_list)
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'] Target indices: [0, 1, 4] The result is : 14
Method 2: Using Direct Index Access
A more direct approach is to access elements by their indices and sum their lengths ?
my_list = ["python", "is", "best", "for", "coders"]
index_list = [0, 1, 4]
result = sum(len(my_list[i]) for i in index_list)
print("Sum of lengths at indices", index_list, "is:", result)
Sum of lengths at indices [0, 1, 4] is: 14
Method 3: Using List Comprehension
We can also use list comprehension to create a list of lengths and then sum them ?
my_list = ["python", "is", "best", "for", "coders"]
index_list = [0, 1, 4]
lengths = [len(my_list[i]) for i in index_list]
print("Lengths at each index:", lengths)
result = sum(lengths)
print("Total sum:", result)
Lengths at each index: [6, 2, 6] Total sum: 14
Comparison
| Method | Time Complexity | Best For |
|---|---|---|
enumerate() |
O(n) | When you need to process all elements |
| Direct Access | O(k) | When you have specific indices (most efficient) |
| List Comprehension | O(k) | When you need intermediate results |
Conclusion
For finding the sum of string lengths at specific indices, direct index access with sum() is the most efficient approach. Use enumerate() when you need to process the entire list or perform additional operations during iteration.
