Python - Find the sum of Length of Strings at given indices
Last Updated :
26 Apr, 2023
Given the String list, write a Python program to compute sum of lengths of custom indices of list.
Examples:
Input : test_list = ["gfg", "is", "best", "for", "geeks"], idx_list = [0, 1, 4]
Output : 10
Explanation : 3 + 2 + 5 = 10. (Sizes of strings at idx.)
Input : test_list = ["gfg", "is", "best", "for", "geeks"], idx_list = [0, 2, 4]
Output : 12
Explanation : 3 + 4 + 5 = 12.
Method #1 : Using len() + loop
In this, we iterate for all indices and check if they occur in index list, if yes, increment frequency in summation counter.
Python3
# Python3 code to demonstrate working of
# Length sum of custom indices Strings
# Using len() + loop
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks"]
# printing original lists
print("The original list is : " + str(test_list))
# initializing idx list
idx_list = [0, 1, 4]
res = 0
for idx, ele in enumerate(test_list):
# adding length if index in idx_list
if idx in idx_list:
res += len(ele)
# printing result
print("Computed Strings lengths sum : " + str(res))
OutputThe original list is : ['gfg', 'is', 'best', 'for', 'geeks']
Computed Strings lengths sum : 10
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using sum() + len() + list comprehension
In this, we perform task of performing summation using sum(), rest all the functionalities are performed as per above method, just as one-liner.
Python3
# Python3 code to demonstrate working of
# Length sum of custom indices Strings
# Using sum() + len() + list comprehension
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks"]
# printing original lists
print("The original list is : " + str(test_list))
# initializing idx list
idx_list = [0, 1, 4]
# performing summation using sum()
# len() used to get strings lengths
res = sum([len(ele) for idx, ele in enumerate(test_list) if idx in idx_list])
# printing result
print("Computed Strings lengths sum : " + str(res))
OutputThe original list is : ['gfg', 'is', 'best', 'for', 'geeks']
Computed Strings lengths sum : 10
The time and space complexity for all the methods are the same:
Time Complexity: O(n)
Space Complexity: O(n)
Approach 3: Using map and lambda function
We can use the map function to apply the length of each element to the given indices.
Python3
test_list = ["gfg", "is", "best", "for", "geeks"]
idx_list = [0, 1, 4]
res = sum(list(map(lambda x: len(test_list[x]), idx_list)))
print("Computed Strings lengths sum :", res)
OutputComputed Strings lengths sum : 10
This approach also has a time complexity of O(n) and an auxiliary space of O(n).
Approach 5: Using the intersection of sets
- Initialize test_list with the list of strings ["gfg", "is", "best", "for", "geeks"].
- Initialize idx_list with the list of indices [0, 1, 4].
- Convert idx_list to a set using set(idx_list). This will make it easier to check if an index is in idx_list.
- Loop through the indices i of test_list using for i in range(len(test_list)).
- Check if i is in idx_set using if i in idx_set. This will determine if the current element in test_list has a matching index in idx_list.
- If i is in idx_set, append the element test_list[i] to matching_elements using [test_list[i] for i in range(len(test_list)) if i in idx_set].
- Once all matching elements have been collected, use sum(len(ele) for ele in matching_elements) to compute the sum of their lengths.
- Assign the result to res.
- Print the result using print("Computed Strings lengths sum : " + str(res)).
Python3
test_list = ["gfg", "is", "best", "for", "geeks"]
idx_list = [0, 1, 4]
# convert the index list to a set
idx_set = set(idx_list)
# use the intersection of sets to get the elements with matching indices
matching_elements = [test_list[i] for i in range(len(test_list)) if i in idx_set]
# sum the lengths of the matching elements
res = sum(len(ele) for ele in matching_elements)
print("Computed Strings lengths sum : " + str(res))
OutputComputed Strings lengths sum : 10
Time complexity: O(n), where n is the length of the input list test_list.
Auxiliary space: O(k), where k is the number of indices in the idx_list that match indices in the test_list.
Similar Reads
Find the length of a set in Python
We are given a set and our task is to find its length. For example, if we have a = {1, 2, 3, 4, 5}, the length of the set should be 5.Using len()len() function in Python returns the number of elements in a set. It provides total count of unique items present in set.Pythona = {1, 2, 3, 4, 5} # Return
2 min read
Find the Index of a Substring in Python
Finding the position of a substring within a string is a common task in Python. In this article, we will explore some simple and commonly used methods to find the index of a substring in Python.Using str.find() The find() method searches for the first occurrence of the specified substring and return
3 min read
Find Length of String in Python
In this article, we will learn how to find length of a string. Using the built-in function len() is the most efficient method. It returns the number of items in a container. Pythona = "geeks" print(len(a)) Output5 Using for loop and 'in' operatorA string can be iterated over, directly in a for loop.
2 min read
Find the Length of a String Without Using len Function in Python
In this article, we will explore different methods to find the length of a string without using the len() function in Python. We will look at several techniques like loops, recursion, and generator expressions. These approaches help us manually calculate the length of a string.Using sum()sum() with
2 min read
How to Find Index of a Substring in Python
In Python, sometimes we need to know where a certain substring appears in a string. To do this, we can find the index (or position) of that substring. The index tells us where the substring is located. Letâs look at some simple ways to find the index of a substring in a string.Using find() methodThe
2 min read
Python | Get the starting index for all occurrences of given substring
Given a string and a substring, the task is to find out the starting index for all the occurrences of a given substring in a string. Let's discuss a few methods to solve the given task. Method #1: Using Naive Method Python3 # Python3 code to demonstrate # to find all occurrences of substring in # a
3 min read
How To Find the Length of a List in Python
The length of a list refers to the number of elements in the list. There are several methods to determine the length of a list in Python. For example, consider a list l = [1, 2, 3, 4, 5], length of this list is 5 as it contains 5 elements in it. Let's explore different methods to find the length of
2 min read
Get Length of a List in Python Without Using Len()
Python len() method is the most common and widely used method for getting the length of a list in Python. But we can use other methods as well for getting the length or size of the list. In this article, we will see how to find the length of a list in Python without using the len() function. Find Th
2 min read
Python - Ways to find indices of value in list
In Python, it is common to locate the index of a particular value in a list. The built-in index() method can find the first occurrence of a value. However, there are scenarios where multiple occurrences of the value exist and we need to retrieve all the indices. Python offers various methods to achi
3 min read
Python - Start and End Indices of words from list in String
Given a String, our task is to write a Python program to extract the start and end index of all the elements of words of another list from a string. Input : test_str = "gfg is best for all CS geeks and engineering job seekers", check_list = ["geeks", "engineering", "best", "gfg"]Output : {'geeks': [
7 min read