Removing a string from a list of strings in Python

In this tutorial, we are going to learn how we can remove a given string from a list of strings in Python. We will be doing this in Python. Let’s see how we can do this.

Ways to remove a string from a list of strings in Python

Python offers many ways to accomplish any programming task. Now, this task can be completed in more than one way. We will be discussing a few of those methods.

Using list comprehension technique

In the following Python program, we are using the list comprehension method to remove a specified string fro a given list of strings. This program checks whether the specified string exists in the list and if so, it removes that string and updates the list. Have a good look at the given example program to understand how it works.

given_list = ["I", "know", "how", "it's", "done"]
string = "how"

new_list = [elem for elem in given_list if elem != string]

print("The given list:", given_list)
print("The new list:", new_list)

 

Output:

The given list: ['I', 'know', 'how', "it's", 'done']
The new list: ['I', 'know', "it's", 'done']

And that is how we can remove a string from a string list using list comprehension technique. Now let’s see some other method to do the same.

Using remove() method with lists

A different approach to remove a string from the list of strings is to use remove() method. This is a built-in method associated with Python lists. This method removes an element from a given list. We pass the element that we want to remove as an argument to this function and this function returns a new list after deleting the passed element from the list. See the below piece of code to understand it better.

given_list = ["I", "know", "how", "it's", "done"]
string = "how"

print("The given list:", given_list)

for elem in given_list:
    if elem == string:
        given_list.remove(elem)

print("The new list:", given_list)

Output:

The given list: ['I', 'know', 'how', "it's", 'done']
The new list: ['I', 'know', "it's", 'done']

Hope it helped. Thank you.

Also read: How to remove all elements from a list in Python

Leave a Reply