Python – Remove strings with any non-required character

PythonServer Side ProgrammingProgramming

When it is required to remove strings, which have a non-required character, a list comprehension and the ‘any’ operator is used.

Below is a demonstration of the same −

Example

 Live Demo

my_list = ["python", "is", "fun", "to", "learn"]

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

my_char_list = ['p', 's', 'l']

print("The character list is :")
print(my_char_list)

my_result = [sub for sub in my_list if not any(element in sub for element in my_char_list )]

print("The resultant list is :")
print(my_result)

Output

The list is :
['python', 'is', 'fun', 'to', 'learn']
The character list is :
['p', 's', 'l']
The resultant list is :
['fun', 'to']

Explanation

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

  • Another list with characters is defined and displayed on the console.

  • A list comprehension is used to iterate over the elements and check if any element is not present in the list.

  • This is stored in a list and assigned to a variable.

  • This is displayed as output on the console.

raja
Published on 04-Sep-2021 10:52:46
Advertisements