Open In App

Python – Extract Indices of substring matches

Last Updated : 05 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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))


Output

The 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))


Output

The 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))


Output

The 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 

  1. Initiate a for loop to traverse list of strings
  2. Check for K in each string using operator.contains() method
  3. If yes append the index of string in list to output list
  4. 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))


Output

The 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))


Output

The 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 | Find all close matches of input string from a list
We are given a list of pattern strings and a single input string. We need to find all possible close good enough matches of input string into list of pattern strings. Examples: Input : patterns = ['ape', 'apple', 'peach', 'puppy'], input = 'appel' Output : ['apple', 'ape'] We can solve this problem in python quickly using in built function difflib.
2 min read
Python | Program that matches a word containing 'g' followed by one or more e's using regex
Prerequisites : Regular Expressions | Set 1, Set 2 Given a string, the task is to check if that string contains any g followed by one or more e's in it, otherwise, print No match. Examples : Input : geeks for geeks Output : geeks geeks Input : graphic era Output : No match Approach : Firstly, make a regular expression (regex) object that matches a
2 min read
Python | Check if suffix matches with any string in given list
Given a list of strings, the task is to check whether the suffix matches any string in the given list. Examples: Input: lst = ["Paras", "Geeksforgeeks", "Game"], str = 'Geeks' Output: TrueInput: lst = ["Geeks", "for", "forgeeks"], str = 'John' Output: False Let's discuss a few methods to do the task. Method #1: Using any() The most concise and read
6 min read
Python | Check if string matches regex list
Sometimes, while working with Python, we can have a problem we have list of regex and we need to check a particular string matches any of the available regex in list. Let's discuss a way in which this task can be performed. Method : Using join regex + loop + re.match() This task can be performed using combination of above functions. In this, we cre
4 min read
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 = 'pine', test_str2 = 'pineapple' Output : [] Explanati
6 min read
NumPy indices() Method | Create Array of Indices
The indices() method returns an array representing the indices of a grid. It computes an array where the subarrays contain index values 0, 1, … varying only along the corresponding axis. Example C/C++ Code import numpy as np gfg = np.indices((2, 3)) print (gfg) Output : [[[0 0 0] [1 1 1]] [[0 1 2] [0 1 2]]]Syntax numpy.indices(dimensions, dtype, sp
2 min read
Python program to extract key-value pairs with substring in a dictionary
Given a dictionary list, extract all the dictionaries which have substring present in particular key. Input : [{"Gfg" : "4", "best" : "1"}, {"Gfg" : "good CS content", "best" : "10"}], K = "Gfg", sub_str = "CS" Output : [{'Gfg': 'good CS content', 'best': '10'}] Explanation : "Gfg" has "CS" as substring value. Input : [{"Gfg" : "4", "best" : "1"},
7 min read
Python Extract Substring Using Regex
Python provides a powerful and flexible module called re for working with regular expressions. Regular expressions (regex) are a sequence of characters that define a search pattern, and they can be incredibly useful for extracting substrings from strings. In this article, we'll explore four simple and commonly used methods to extract substrings usi
2 min read
Python | Extract key-value of dictionary in variables
Sometimes, while working with dictionaries, we can face a problem in which we may have just a singleton dictionary, i.e dictionary with just a single key-value pair, and require to get the pair in separate variables. This kind of problem can come in day-day programming. Let's discuss certain ways in which this can be done. Method #1: Using items()
5 min read
Python Regex to extract maximum numeric value from a string
Given an alphanumeric string, extract maximum numeric value from that string. Alphabets will only be in lower case. Examples: Input : 100klh564abc365bgOutput : 564Maximum numeric value among 100, 564 and 365 is 564.Input : abchsd0sdhsOutput : 0Python Regex to extract maximum numeric value from a stringThis problem has existing solution please refer
2 min read
three90RightbarBannerImg