Python - Filter Supersequence Strings

When we need to filter strings that contain all characters from a given subsequence, we use a list comprehension with the all() function. This technique finds supersequence strings ? strings that contain every character from a target substring.

What is a Supersequence?

A supersequence is a string that contains all characters of another string (subsequence), though not necessarily in consecutive order. For example, "alwaysgreat" is a supersequence of "ys" because it contains both 'y' and 's'.

Example

Here's how to filter strings containing all characters from a given substring ?

my_list = ["Python", "/", "is", "alwaysgreat", "to", "learn"]

print("The list is :")
print(my_list)

substring = "ys"

my_result = [sub for sub in my_list if all(elem in sub for elem in substring)]

print("The resultant string is :")
print(my_result)
The list is :
['Python', '/', 'is', 'alwaysgreat', 'to', 'learn']
The resultant string is :
['alwaysgreat']

How It Works

The list comprehension uses all(elem in sub for elem in substring) to check if every character in the substring exists in the current string. The all() function returns True only when all conditions are met.

Multiple Character Example

Let's see another example with more complex filtering ?

words = ["programming", "python", "coding", "algorithms", "syntax"]
target = "pyt"

filtered_words = [word for word in words if all(char in word for char in target)]

print("Words containing all characters from 'pyt':")
print(filtered_words)
Words containing all characters from 'pyt':
['python']

Key Points

  • The all() function checks if all elements in an iterable are True

  • Characters don't need to be consecutive in the supersequence

  • The order of characters in the substring doesn't matter

  • Case-sensitive matching is performed

Conclusion

Use list comprehension with all() to filter supersequence strings efficiently. This method checks if every character from a target substring exists within each string in your list.

---
Updated on: 2026-03-26T02:11:46+05:30

212 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements