Elements from the list (including strings) can be deleted using the remove() function.
This code removes the specific single string.
1 2 3 |
my_list = ['one', 'two', 'three', 'two'] my_list.remove('two') print(my_list) |
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.
1 2 |
my_list = ['one', 'two', 'three', 'two'] print(list(filter(lambda a: a != 'two', my_list))) |
Another way to achieve the same result is to use list comprehension.
1 2 |
my_list = ['one', 'two', 'three', 'two'] print([value for value in my_list if value != 'two']) |
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.
1 2 3 |
my_list = ['one', 2, 3, 'two'] filtered_list = list(filter(lambda i: not(type(i) is str), my_list)) print(filtered_list) |
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.
1 2 3 4 5 6 7 8 9 10 11 |
my_list = ['one', 2, 3, 'two'] if type(my_list[2]) is str: my_list.pop(2) print(my_list) if type(my_list[3]) is str: my_list.pop(3) print(my_list) |
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]