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 - Test if any set element exists in List
Next article icon

Python – Test if string contains element from list

Last Updated : 08 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Testing if string contains an element from list is checking whether any of the individual items in a list appear within a given string.

Using any() with a generator expression

any() is the most efficient way to check if any element from the list is present in the list.

Python
s = "Python is powerful and versatile." el = ["powerful", "versatile", "fast"]  # Check if any element in the list exists in the string  # using any() and a generator expression res = any(elem in s for elem in el) print(res)  

Output
True 

Explanation:

  • The any() function evaluates if at least one element in the generator expression is True.
  • The generator expression iterates through the list and checks each element’s presence in the string using the ‘in’ operator.
  • This approach is efficient as it short-circuits and stops processing once a match is found.

Let’s explore some more methods to check how we can test if string contains elements from a list.

Table of Content

  • Using a for loop
  • Using set intersection
  • Using regular expressions

Using a for loop

This approach explicitly iterates through the list using a for loop to check for the presence of elements in the string.

Python
s = "Python is powerful and versatile." el = ["powerful", "versatile", "fast"]  # Initialize the result variable to False res = False  # Iterate through each element in the list for elem in el:     if elem in s:         res = True         break  print(res) 

Output
True 

Explanation:

  • The loop iterates through each element in the list ‘el’ and checks if it exists in the string ‘s’ using the ‘in’ operator.
  • If a match is found, the loop exits early using break, which saves unnecessary iterations.

Using set intersection

Using set intersection method is effective when both the string and the list of elements are relatively short.

Python
s = "Python is powerful and versatile." el = ["powerful", "versatile", "fast"]  # Split the string into individual words using the split() method' res = bool(set(s.split()) & set(el))  print(res)  

Output
True 

Explanation:

  • The split() method breaks the string into individual words and sets are created from the string and list elements.
  • The & operator computes the intersection of the two sets to check for common elements.

Using regular expressions

Regular expressions provide flexibility for more complex matching scenarios but are less efficient for simple tasks.

Python
import re  s = "Python is powerful and versatile." el = ["powerful", "versatile", "fast"]  # Compile a regular expression pattern to search for any of the elements in the list pattern = re.compile('|'.join(map(re.escape, el))) res = bool(pattern.search(s)) print(res)   

Output
True 

Explanation:

  • The join() method creates a single pattern from the list of elements, separated by | (logical OR).
  • The re.compile() function compiles the pattern for faster matching and search checks for its presence in the string.
  • This method is less efficient for simple substring checks due to overhead from compiling patterns.


Next Article
Python - Test if any set element exists in List
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Python - Check if List contains elements in Range
    Checking if a list contains elements within a specific range is a common problem. In this article, we will various approaches to test if elements of a list fall within a given range in Python. Let's start with a simple method to Test whether a list contains elements in a range. Using any() Function
    3 min read
  • Python | Test if any list element returns true for condition
    Sometimes, while coding in Python, we can have a problem in which we need to filter a list on basis of condition met by any of the element. This can have it's application in web development domain. Let's discuss a shorthand in which this task can be performed. Method : Using any() + list comprehensi
    4 min read
  • Python - Test if any set element exists in List
    Given a set and list, the task is to write a python program to check if any set element exists in the list. Examples: Input : test_dict1 = test_set = {6, 4, 2, 7, 9, 1}, test_list = [6, 8, 10] Output : True Explanation : 6 occurs in list from set. Input : test_dict1 = test_set = {16, 4, 2, 7, 9, 1},
    4 min read
  • Python - Test if tuple list has Single element
    Given a Tuple list, check if it is composed of only one element, used multiple times. Input : test_list = [(3, 3, 3), (3, 3), (3, 3, 3), (3, 3)] Output : True Explanation : All elements are equal to 3. Input : test_list = [(3, 3, 3), (3, 3), (3, 4, 3), (3, 3)] Output : False Explanation : All elemen
    8 min read
  • Python - String concatenation in Heterogeneous list
    Sometimes, while working with Python, we can come across a problem in which we require to find the concatenation of strings. This problem is easier to solve. But this can get complex cases we have a mixture of data types to go along with it. Let’s discuss certain ways in which this task can be perfo
    4 min read
  • Python - Check if string starts with any element in list
    We need to check if a given string starts with any element from a list of substrings. Let's discuss different methods to solve this problem. Using startswith() with tuplestartswith() method in Python can accept a tuple of strings to check if the string starts with any of them. This is one of the mos
    3 min read
  • Check if any element in list satisfies a condition-Python
    The task of checking if any element in a list satisfies a condition involves iterating through the list and returning True if at least one element meets the condition otherwise, it returns False. For example, in a = [4, 5, 8, 9, 10, 17], checking ele > 10 returns True as 17 satisfies the conditio
    3 min read
  • Python - Find Index containing String in List
    In this article, we will explore how to find the index of a string in a list in Python. It involves identifying the position where a specific string appears within the list. Using index()index() method in Python is used to find the position of a specific string in a list. It returns the index of the
    3 min read
  • Python | Even Front digits Test in List
    Sometimes we may face a problem in which we need to find a list if it contains numbers that are even. This particular utility has an application in day-day programming. Let’s discuss certain ways in which this task can be achieved. Method #1: Using list comprehension + map() We can approach this pro
    5 min read
  • Python | Convert string enclosed list to list
    Given a list enclosed within a string (or quotes), write a Python program to convert the given string to list type. Examples: Input : "[0, 2, 9, 4, 8]" Output : [0, 2, 9, 4, 8] Input : "['x', 'y', 'z']" Output : ['x', 'y', 'z'] Approach #1: Python eval() The eval() method parses the expression passe
    5 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