Python - Extract Indices of substring matches
Last Updated :
05 May, 2023
Given a String List, and a substring, extract list of indices of Strings, in which that substring occurs.
Input : test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Gfg is useful"], K = "Gfg"
Output : [0, 2, 3]
Explanation : "Gfg" is present in 0th, 2nd and 3rd element as substring.
Input : test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Gfg is useful"], K = "good"
Output : [0]
Explanation : "good" is present in 0th substring.
Method #1: Using loop + enumerate()
This is the brute way in which this task can be done. In this, we iterate for all the elements along with their indices using enumerate(), and conditional statements are used to get the required result.
Python3
# Python3 code to demonstrate working of
# Extract Indices of substring matches
# Using loop + enumerate()
# initializing list
test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Its useful"]
# initializing K
K = "Gfg"
# printing original list
print("The original list : " + str(test_list))
# using loop to iterate through list
res = []
for idx, ele in enumerate(test_list):
if K in ele:
res.append(idx)
# printing result
print("The indices list : " + str(res))
OutputThe original list : ['Gfg is good', 'for Geeks', 'I love Gfg', 'Its useful']
The indices list : [0, 2]
Time complexity : O(n*m)
Space Complexity : O(n)
Method #2 : Using list comprehension + enumerate()
This is yet another way in which this task can be solved. In this, we perform the similar task as above method using list comprehension and enumerate() is used to get compact solution.
Python3
# Python3 code to demonstrate working of
# Extract Indices of substring matches
# Using list comprehension + enumerate()
# initializing list
test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Its useful"]
# initializing K
K = "Gfg"
# printing original list
print("The original list : " + str(test_list))
# using list comprehension and enumerate to offer compact solution
res = [idx for idx, val in enumerate(test_list) if K in val]
# printing result
print("The indices list : " + str(res))
OutputThe original list : ['Gfg is good', 'for Geeks', 'I love Gfg', 'Its useful']
The indices list : [0, 2]
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3 : Using find() method
Python3
# Python3 code to demonstrate working of
# Extract Indices of substring matches
# initializing list
test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Its useful"]
# initializing K
K = "Gfg"
# printing original list
print("The original list : " + str(test_list))
# using loop to iterate through list
res = []
for i in range(0,len(test_list)):
if test_list[i] .find(K)!=-1 :
res.append(i)
# printing result
print("The indices list : " + str(res))
OutputThe original list : ['Gfg is good', 'for Geeks', 'I love Gfg', 'Its useful']
The indices list : [0, 2]
Time complexity : O(n*m)
Space Complexity : O(n)
Method #5 : Using operator.contains() method
Approach
- Initiate a for loop to traverse list of strings
- Check for K in each string using operator.contains() method
- If yes append the index of string in list to output list
- Display output list
Python3
# Python3 code to demonstrate working of
# Extract Indices of substring matches
# initializing list
test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Its useful"]
# initializing K
K = "Gfg"
# printing original list
print("The original list : " + str(test_list))
# using loop to iterate through list
res = []
import operator
for i in range(0,len(test_list)):
if(operator.contains(test_list[i],K)):
res.append(i)
# printing result
print("The indices list : " + str(res))
OutputThe original list : ['Gfg is good', 'for Geeks', 'I love Gfg', 'Its useful']
The indices list : [0, 2]
Time Complexity : O(M*N) M - length of strings list N -length of each string
Auxiliary Space : O(N) N - number of strings with K as substring
Method #6: Using map() function + lambda function
Another approach to solve the given problem is by using the map() function along with the lambda function. The map() function applies a function to each element of a sequence and returns an iterator of the results.
step-by-step approach
Initialize the list and substring K.
Use the map() function to apply the lambda function to each element of the list and get a list of True/False values indicating if the substring K is present in the element or not.
Convert the list of True/False values into a list of 1's and 0's using the map() function and another lambda function.
Use the enumerate() function to get the indices of the list of 1's and 0's.
Extract the indices of the elements that have 1 in the list of 1's and 0's.
Print the result.
Python3
# Python3 code to demonstrate working of
# Extract Indices of substring matches
# initializing list
test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Its useful"]
# initializing K
K = "Gfg"
# printing original list
print("The original list : " + str(test_list))
# using map() function with lambda function to get the list of True/False values
bool_list = list(map(lambda x: K in x, test_list))
# using map() function with lambda function to convert bool_list into a list of 1's and 0's
int_list = list(map(lambda x: 1 if x else 0, bool_list))
# using enumerate() function to get the indices of the int_list
enum_list = list(enumerate(int_list))
# extracting the indices of the elements that have 1 in the int_list
res = [i for i, j in enum_list if j == 1]
# printing result
print("The indices list : " + str(res))
OutputThe original list : ['Gfg is good', 'for Geeks', 'I love Gfg', 'Its useful']
The indices list : [0, 2]
Time Complexity: O(n), where n is the number of elements in the list.
Auxiliary Space: O(n), where n is the number of elements in the list.
Similar Reads
Python - Extract indices of Present, Non Index matching Strings Given two strings, extract indices of all characters from string 1 which are present in the other string, but not in the same index. Input : test_str1 = 'pplg', test_str2 = 'pineapple' Output : [0, 1, 2] Explanation : ppl is found in 2nd string, also not on same index as 1st. Input : test_str1 = 'pi
6 min read
Python - Extract K length substrings The task is to extract all possible substrings of a specific length, k. This problem involves identifying and retrieving those substrings in an efficient way. Let's explore various methods to extract substrings of length k from a given string in PythonUsing List Comprehension List comprehension is t
2 min read
Python | Substring Key match in dictionary Sometimes, while working with dictionaries, we might have a use case in which we are not known the exact keys we require but just a specific part of keys that we require to fetch. This kind of problem can arise in many applications. Let's discuss certain ways in which this problem can be solved. Met
9 min read
Extract List of Substrings in List of Strings in Python Working with strings is a fundamental aspect of programming, and Python provides a plethora of methods to manipulate and extract substrings efficiently. When dealing with a list of strings, extracting specific substrings can be a common requirement. In this article, we will explore five simple and c
3 min read
Python - Get match indices Getting match indices in Python involves identifying the positions of specific substrings or patterns within a string. It helps in locating where a certain sequence occurs, facilitating further operations based on those positions. In this article, we will see How to match indices in a list. Using Di
2 min read