Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Get all substrings of given string
Next article icon

Python – Find all the strings that are substrings to the given list of strings

Last Updated : 21 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 substring.

Input : test_list1 = [“geeksforgeeks”, “best”, “4”, “geeks”], test_list2 = [“Geeks”, “win”, “or”, “learn”]

Output : []

Explanation : No substrings found.

Method #1: Using list comprehension

In this, we perform task of using nested loop and testing using list comprehension, extracting the string if its part of any substring of other list.

Python3




# Python3 code to demonstrate working of
# Substring Intersections
# Using list comprehension
 
# initializing lists
test_list1 = ["Geeksforgeeks", "best", "for", "geeks"]
test_list2 = ["Geeks", "win", "or", "learn"]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# using list comprehension for nested loops
res = list(
    set([ele1 for sub1 in test_list1 for ele1 in test_list2 if ele1 in sub1]))
 
# printing result
print("Substrings Intersections : " + str(res))
 
 
Output
The original list 1 is : ['Geeksforgeeks', 'best', 'for', 'geeks'] The original list 2 is : ['Geeks', 'win', 'or', 'learn'] Substrings Intersections : ['or', 'Geeks']

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

Method #2: Using any() + generator expression

In this, any() is used to check for substring matching in any of the strings from the string list to be matched in.

Python3




# Python3 code to demonstrate working of
# Substring Intersections
# Using any() + generator expression
 
# initializing lists
test_list1 = ["Geeksforgeeks", "best", "for", "geeks"]
test_list2 = ["Geeks", "win", "or", "learn"]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# any() returns the string after match in any string
# as Substring
res = [ele2 for ele2 in test_list2 if any(ele2 in ele1 for ele1 in test_list1)]
 
# printing result
print("Substrings Intersections : " + str(res))
 
 
Output
The original list 1 is : ['Geeksforgeeks', 'best', 'for', 'geeks'] The original list 2 is : ['Geeks', 'win', 'or', 'learn'] Substrings Intersections : ['Geeks', 'or']

Time Complexity: O(n2)

Space Complexity: O(n)

Method #3: Using find() method

Python3




# Python3 code to demonstrate working of
# Substring Intersections
 
# initializing lists
test_list1 = ["Geeksforgeeks", "best", "for", "geeks"]
test_list2 = ["Geeks", "win", "or", "learn"]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
res=[]
for i in test_list2:
    for j in test_list1:
        if(j.find(i)!=-1 and i not in res):
            res.append(i)
 
# printing result
print("Substrings Intersections : " + str(res))
 
 
Output
The original list 1 is : ['Geeksforgeeks', 'best', 'for', 'geeks'] The original list 2 is : ['Geeks', 'win', 'or', 'learn'] Substrings Intersections : ['Geeks', 'or']

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

Method#4: Using Recursive method.

we define a recursive function substring_intersections() that takes in two lists of strings as input. It first checks if the second list list2 is empty. If it is, the function returns an empty list [].

If the second list list2 is not empty, the function checks if the first string in list2 is a substring of any element in the first list list1. If it is, it appends it to the result list res.

The function then recursively calls itself with the first element of list2 removed and the same first list list1. The result of this recursive call is concatenated with the result list res.

Finally, the function returns the result list res.

Python3




# printing resultdef substring_intersections(list1, list2):
# Substring Intersections
 
def substring_intersections(list1, list2):
    if not list2:
        return []
    res = []
    for ele1 in list1:
        if list2[0] in ele1:
            res.append(list2[0])
            break
    res += substring_intersections(list1, list2[1:])
    return res
# initializing lists
 
test_list1 = ["Geeksforgeeks", "best", "for", "geeks"]
test_list2 = ["Geeks", "win", "or", "learn"]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
res = substring_intersections(test_list1, test_list2)
 
# printing result
print("Substrings Intersections : " + str(res))
#this code contributed by tvsk
 
 
Output
The original list 1 is : ['Geeksforgeeks', 'best', 'for', 'geeks'] The original list 2 is : ['Geeks', 'win', 'or', 'learn'] Substrings Intersections : ['Geeks', 'or']

The time complexity of this recursive approach is O(n * m * k) where n, m and k are the lengths of the two input lists and the maximum length of a string in the input lists.

 The space complexity is O(k) where k is the maximum length of a string in the input lists.

Method 5 :  use is the set intersection method. 

 steps for this approach:

Convert both test_list1 and test_list2 to sets, which removes any duplicate elements and makes checking for intersections faster.
Take the intersection of the two sets using the “&” operator.
Convert the resulting set back to a list.

Python3




# Python3 code to demonstrate working of
# Substring Intersections
 
# initializing lists
test_list1 = ["Geeksforgeeks", "best", "for", "geeks"]
test_list2 = ["Geeks", "win", "or", "learn"]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
res=[]
for i in test_list2:
    for j in test_list1:
        if(j.find(i)!=-1 and i not in res):
            res.append(i)
 
# printing result
print("Substrings Intersections : " + str(res))
 
 
Output
The original list 1 is : ['Geeksforgeeks', 'best', 'for', 'geeks'] The original list 2 is : ['Geeks', 'win', 'or', 'learn'] Substrings Intersections : ['Geeks', 'or'] 

The time complexity of this approach is O(mnk), where m and n are the lengths of test_list1 and test_list2, respectively, and k is the maximum length of a substring in either list. 

The space complexity is O(k) for storing the res list.



Next Article
Python - Get all substrings of given string
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Python program to split a string by the given list of strings
    Given a list of strings. The task is to split the string by the given list of strings. Input : test_str = 'geekforgeeksbestforgeeks', sub_list = ["best"] Output : ['geekforgeeks', 'best', 'forgeeks'] Explanation : "best" is extracted as different list element. Input : test_str = 'geekforgeeksbestfor
    4 min read
  • Python | Get the substring from given string using list slicing
    Given a string, write a Python program to get the substring from given string using list slicing. Let’s try to get this using different examples. What is substring? A substring is a portion of a string. Python offers a variety of techniques for producing substrings, as well as for determining the in
    4 min read
  • Finding Strings with Given Substring in List - Python
    The task of finding strings with a given substring in a list in Python involves checking whether a specific substring exists within any of the strings in a list. The goal is to efficiently determine if the desired substring is present in any of the elements of the list. For example, given a list a =
    3 min read
  • Print Substrings that are Prefix of the Given String - Python
    The task of printing the substrings that are prefixes of a given string involves generating all the possible substrings that start from the first character of the string and end at any subsequent position.For example, if the given string is s = "hello", the prefixes of the string would include "h",
    3 min read
  • Python - Get all substrings of given string
    A substring is any contiguous sequence of characters within the string. We'll discuss various methods to extract this substring from a given string by using a simple approach. Using List Comprehension :List comprehension offers a concise way to create lists by applying an expression to each element
    3 min read
  • Python - Filter list of strings based on the substring list
    The problem requires to check which strings in the main list contain any of the substrings from a given list and keep only those that match. Let us explore this problem and understand different methods to solve it. Using list comprehension with any() (Most Efficient)List comprehension is a concise a
    4 min read
  • Python program to find the occurrence of substring in the string
    Given a list of words, extract all the indices where those words occur in the string. Input : test_str = 'geeksforgeeks is best for geeks and cs', test_list = ["best", "geeks"] Output : [2, 4] Explanation : best and geeks occur at 2nd and 4th index respectively. Input : test_str = 'geeksforgeeks is
    4 min read
  • Python | Remove the given substring from end of string
    Sometimes we need to manipulate our string to remove extra information from the string for better understanding and faster processing. Given a task in which the substring needs to be removed from the end of the string using Python. Remove the substring from the end of the string using Slicing In thi
    3 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 C/C++ Code # Python3 code to demonstrate # to find all occurrences of substring in #
    3 min read
  • Create List of Substrings from List of Strings in Python
    In Python, when we work with lists of words or phrases, we often need to break them into smaller pieces, called substrings. A substring is a contiguous sequence of characters within a string. Creating a new list of substrings from a list of strings can be a common task in various applications. In th
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences