Open In App

Python – Substring presence in Strings List

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

Given list of substrings and list of string, check for each substring, if they are present in any of strings in List.

Input : test_list1 = [“Gfg”, “is”, “best”], test_list2 = [“I love Gfg”, “Its Best for Geeks”, “Gfg means CS”] 
Output : [True, False, False] 
Explanation : Only Gfg is present as substring in any of list String in 2nd list. 

Input : test_list1 = [“Gfg”, “is”, “best”], test_list2 = [“I love Gfg”, “It is Best for Geeks”, “Gfg means CS”] 
Output : [True, True, False] 
Explanation : Only Gfg and is are present as substring in any of list String in 2nd list.

Method #1 : Using loop

This is brute way in which this task can be performed. In this, we for, each element in list check if it’s substring of any of other list’s element. 

Python3




# Python3 code to demonstrate working of
# Substring presence in Strings List
# Using loop
 
# initializing lists
test_list1 = ["Gfg", "is", "Best"]
test_list2 = ["I love Gfg", "Its Best for Geeks", "Gfg means CS"]
 
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
 
# using loop to iterate
res = []
for ele in test_list1 :
  temp = False
   
  # inner loop to check for
  # presence of element in any list
  for sub in test_list2 :
    if ele in sub:
      temp = True
      break   
  res.append(temp)
   
# printing result
print("The match list : " + str(res))


Output

The original list 1 : ['Gfg', 'is', 'Best']
The original list 2 : ['I love Gfg', 'Its Best for Geeks', 'Gfg means CS']
The match list : [True, False, True]

Time complexity: O(nlogn), where n is the length of the test_list. The loop takes O(n*n) time
Auxiliary Space: O(n), extra space of size n is required

Method #2 : Using list comprehension + any()

The combination of above functions can be used to solve this problem. In this, we check for any sublist using any() and list comprehension is used to perform iteration.

Python3




# Python3 code to demonstrate working of
# Substring presence in Strings List
# Using list comprehension + any()
 
# initializing lists
test_list1 = ["Gfg", "is", "Best"]
test_list2 = ["I love Gfg", "Its Best for Geeks", "Gfg means CS"]
 
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
 
# any() reduces a nesting
# checks for element presence in all Substrings
res = [True if any(i in j for j in test_list2) else False for i in test_list1]
 
# printing result
print("The match list : " + str(res))


Output

The original list 1 : ['Gfg', 'is', 'Best']
The original list 2 : ['I love Gfg', 'Its Best for Geeks', 'Gfg means CS']
The match list : [True, False, True]

The Time and Space Complexity for all the methods are the same:

Time Complexity: O(n)
Space Complexity: O(n)

Method 3:  using the built-in set and intersection functions. 

 steps to implement this approach:

  • Convert both test_list1 and test_list2 to sets using the set function.
  • Compute the intersection of the two sets using the intersection function.
  • Convert the result back to a list using the list function.
  • For each string in test_list1, check if it is in the resulting list from step 3.
  • Append the result of the check to the final result list.
  • Print the final result list.

Python3




# Python3 code to demonstrate working of
# Substring presence in Strings List
# Using set intersection
 
# initializing lists
test_list1 = ["Gfg", "is", "Best"]
test_list2 = ["I love Gfg", "Its Best for Geeks", "Gfg means CS"]
 
# convert to sets and compute intersection
set1 = set(test_list1)
set2 = set(" ".join(test_list2).split())
intersection = set1.intersection(set2)
 
# convert intersection back to list
intersection_list = list(intersection)
 
# initialize result list
result = []
 
# check if each string in test_list1 is in the intersection list
for string in test_list1:
    if string in intersection_list:
        result.append(True)
    else:
        result.append(False)
 
# print result
print("The match list : " + str(result))


Output

The match list : [True, False, True]

Time complexity of this approach is O(n+m), where n is the length of test_list1 and m is the total length of all strings in test_list2. 

The auxiliary space complexity is O(n+m) to store the sets and intersection.

Method 4:  using numpy:

Algorithm:

  1. Import the required module numpy as np.
  2. Initialize two numpy arrays arr1 and arr2 with the given values.
  3. Print the original lists.
  4. Create a new numpy array res using list comprehension, where each element in the array is True if the
  5. corresponding element in arr1 is present in any element of arr2, False otherwise.
  6. Print the match list.

Python3




import numpy as np
 
# initializing arrays
arr1 = np.array(["Gfg", "is", "Best"])
arr2 = np.array(["I love Gfg", "Its Best for Geeks", "Gfg means CS"])
# printing original lists
print("The original list 1 : " + str(arr1))
print("The original list 2 : " + str(arr2))
# find if substring is present
res = np.array([any(np.char.find(arr2, i) != -1) for i in arr1])
 
# printing result
print("The match list : ", res)
#This code is contributed by Vinay Pinjala


Output:
The original list 1 : ['Gfg' 'is' 'Best']
The original list 2 : ['I love Gfg' 'Its Best for Geeks' 'Gfg means CS']
The match list :  [ True False  True]

Time complexity:
The time complexity is O(nmk), where n is the length of arr1, m is the length of arr2, and k is the length of the longest string in arr2.

Space complexity:
The space complexity  is O(nm), as we create a new numpy array with nm elements.



Similar Reads

Python | Filter tuples according to list element presence
Sometimes, while working with records, we can have a problem in which we have to filter all the tuples from a list of tuples, which contains atleast one element from a list. This can have applications in many domains working with data. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehension Using list com
8 min read
Python | Filter list of strings based on the substring list
Given two lists of strings string and substr, write a Python program to filter out all the strings in string that contains string in substr. Examples: Input : string = ['city1', 'class5', 'room2', 'city2']substr = ['class', 'city']Output : ['city1', 'class5', 'city2'] Input : string = ['coordinates', 'xyCoord', '123abc']substr = ['abc', 'xy']Output
8 min read
Python | Finding strings with given substring in list
Method #1: Using list comprehension List comprehension is an elegant way to perform any particular task as it increases readability in the long run. This task can be performed using a naive method and hence can be reduced to list comprehension as well. C/C++ Code # Python code to demonstrate # to find strings with substrings # using list comprehens
8 min read
Python | Check if substring is part of List of Strings
Many problems of substrings have been dealt with many times. There can also be such problem in which we require to check if argument string is a part of any of the strings coming in the input list of strings. Let's discuss various ways in which this can be performed. Method #1 : Using join() The basic approach that can be employed to perform this p
5 min read
Python | Replace substring in list of strings
While working with strings, one of the most used application is replacing the part of string with another. Since string in itself is immutable, the knowledge of this utility in itself is quite useful. Here the replacement of a substring in list of string is performed. Let's discuss certain ways in which this can be performed. Method #1 : Using list
6 min read
Python - Count Strings with substring String List
The classical problem that can be handled quite easily by python and has been also dealt with many times is finding if a string is substring of other. But sometimes, one wishes to extend this on list of strings and find how many strings satisfy condition, and hence then requires to traverse the entire container and perform the generic algorithm. Le
7 min read
Python - All occurrences of Substring from the list of strings
Given a list of strings and a list of substring. The task is to extract all the occurrences of a substring from the list of strings. Examples: Input : test_list = ["gfg is best", "gfg is good for CS", "gfg is recommended for CS"] subs_list = ["gfg", "CS"] Output : ['gfg is good for CS', 'gfg is recommended for CS'] Explanation : Result strings have
5 min read
Python | Remove empty strings from list of strings
In many scenarios, we encounter the issue of getting an empty string in a huge amount of data and handling that sometimes becomes a tedious task. Let's discuss certain way-outs to remove empty strings from list of strings. Method #1: Using remove() This particular method is quite naive and not recommended use, but is indeed a method to perform this
7 min read
Python | Tokenizing strings in list of strings
Sometimes, while working with data, we need to perform the string tokenization of the strings that we might get as an input as list of strings. This has a usecase in many application of Machine Learning. Let's discuss certain ways in which this can be done. Method #1 : Using list comprehension + split() We can achieve this particular task using lis
3 min read
Python - Find all the strings that are substrings to the given list of strings
Given two lists, the task is to write a Python program to extract all the strings which are possible substring to any of strings in another list. Example: Input : test_list1 = ["Geeksforgeeks", "best", "for", "geeks"], test_list2 = ["Geeks", "win", "or", "learn"] Output : ['Geeks', 'or'] Explanation : "Geeks" occurs in "Geeksforgeeks string as subs
5 min read
three90RightbarBannerImg