Remove a String From a List in Python

Elements from the list (including strings) can be deleted using the remove() function.

This code removes the specific single string.

The first string that meets the condition is removed. If there are more identical strings, they are going to stay inside the list.

['one', 'three', 'two']

Remove all matching strings

You can also remove all matching elements from the list by using the lambda function.

Another way to achieve the same result is to use list comprehension.

Both examples clear all matching elements from the list.

['one', 'three']

Remove all elements that are strings

You can also remove all elements that match the particular type. In this case, we want to get rid of list elements that are strings.

For this task, we are going to use the lambda function one more time.

The filtered list removes all string values and returns the rest. In our case, these are 2 and 3.

[2, 3]

Remove the element at the index if it’s a string

If you want to remove an element at a particular index only if the value is a string, you can use the pop() function.

In the first condition, we check whether the value at index 2 (counting starts from 0) is a string. It’s not, therefore not a single element is removed.

In the next check, the element ‘two’ is a string. The condition is met, therefore the function pop() removes this value.

['one', 2, 3, 'two']
['one', 2, 3]