How to Remove List Elements Starting with a Given String in Python?

Estimated read time 1 min read

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

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

# Remove list elements starting with "apple"
new_list = [x for x in original_list if not x.startswith("apple")]

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

In this code, we define an original list (original_list) that contains elements we want to remove that start with 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 start with the string “apple”. The startswith() function is used to check if each element starts with the given string.

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

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply