How to Remove List Elements Containing a Given String in Python?

Estimated read time 1 min read

To remove list elements containing a given string in Python, you can use a list comprehension with a conditional statement that checks if the given string is not in the element. Here is an example code snippet that removes list elements containing the string “apple”:

original_list = ["apple", "banana", "apple pie", "pear", "kiwi"]

# Remove list elements containing "apple"
new_list = [x for x in original_list if "apple" not in x]

print(new_list)  # Output: ["banana", "pear", "kiwi"]

In this code, we define an original list (original_list) that contains elements we want to remove that contain the string “apple”.

Next, we create a new list (new_list) using a list comprehension that includes only the elements from the original list that do not contain the string “apple”. The in keyword is used to check if the given string is in each element.

Finally, we print the new list (new_list) that does not contain the elements containing the string “apple”.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply