Open In App

How to check if multiple Strings exist in a list

Last Updated : 02 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Checking if multiple strings exist in a list is a common task in Python. This can be useful when we are searching for keywords, filtering data or validating inputs. Let's explore various ways to check if multiple strings exist in a list.

Using Set Operations (most efficient)

The most efficient way to check if multiple strings exist in a list is by using Python's set operations. This method is fast and concise especially for large lists.

Python
a = ["apple", "banana", "cherry", "date"]

# Strings to check
s = {"banana", "date"}

# Check if all strings exist in the list
if s.issubset(a):
    print("Found")
else:
    print("Not Found")


This method is efficient as set operations have average time complexity of O(1) for membership checks.

Let's see some more methods to check if multiple strings in a exist in a list

Using List Comprehension

List comprehension provides a clean way to check for multiple strings.

Python
l = ["apple", "banana", "cherry", "date"]

# Strings to check

s = ["banana", "date"]

# Check if all strings exist in the list
if all(item in l for item in s):
    print("All strings are present.")

else:

    print("Some strings are missing.")

all() function iterates through the list comprehension checking if each string in 's' is 'l'.

Using a loop

Using a loop is a straightforward way to check if multiple strings exist or not for beginners.

Python
a = ["apple", "banana", "cherry", "date"]

# Strings to check
s = ["banana", "date"]

# Check using a loop
all_present = True

for item in s:
    if item not in a:
        all_present = False

        break

if all_present:
    print("Found")
else:
    print("Not Found")

A loop iterates through 's' and checks each string against the list. If any string is not found the loop breaks early for efficiency.

Using filter()

filter() function can be used to extract matching strings and compare the result.

Python
a = ["apple", "banana", "cherry", "date"]

# Strings to check
s = ["banana", "date"]

# Check if all strings match
matching = list(filter(lambda x: x in a, s))

if len(matching) == len(s):
    print("Found")
else:
    print("Not Found")

filter() checks if each string in 's' exists in 'l' and returns the matches and compares the length of the matches to the original list of strings.


Next Article
Practice Tags :

Similar Reads