Python - Filter Supersequence Strings

PythonServer Side ProgrammingProgramming

When it is required to filter supersequence strings, a simple list comprehension is used.

Example

Below is a demonstration of the same

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)

Output

The list is :
['Python', '/', 'is', 'alwaysgreat', 'to', 'learn']
The resultant string is :
['alwaysgreat']

Explanation

  • A list is defined and is displayed on the console.

  • A substring is defined.

  • The list comprehension is used to iterate through the elements using the ‘all’ clause.

  • This is assigned to a variable.

  • This is the output that is displayed on the console.

raja
Published on 15-Sep-2021 12:27:07
Advertisements