Remove All Occurrences of Character in List in Python (4 Examples)
This post illustrates how to remove all occurrences of a certain character from a list of strings in the Python programming language.
The content of the tutorial is structured as follows:
Let’s dive right into the examples!
Creation of Example Data
As the first step, I’ll have to create some data that we can use in the following examples:
my_list = ['a', 'b', 'a', 'b', 'e', 'a', 'b', 'e'] # initializing sample list print(my_list) # printing initial list # ['a', 'b', 'a', 'b', 'e', 'a', 'b', 'e']
Example 1: Remove All Occurrences with List Comprehension
In our first solution, we utilize list comprehension to remove all occurrences of a character. We set the condition if i != char_to_delete
to select only the characters other than char_to_delete
. Also, since we need to use the sample list for multiple examples, we will copy the list first and then employ the operations. You can skip copying the list step in regular use.
char_to_delete = 'a' # assigning the char to remove my_copy = my_list.copy() # copying the list my_copy = [i for i in my_copy if i != char_to_delete] # removing all char 'a' elements from the list print(my_copy) # printing the updated list # ['b', 'b', 'e', 'b', 'e']
Have a look at the previous output of the Python console. As you can see, the list has no ‘a’ characters anymore, and the remaining elements are in their original order.
Example 2: Remove All Occurrences with while Loop (Naive Approach)
Example 2 shows how to remove the characters in a naive way by using a while loop. This means iterating through the list and checking if the current character is char_to_delete
. If it is, it removes the character, if it is not, it continues with the next character. It repeats the procedure until there is no unchecked element.
char_to_delete = 'b' # assigning the char to remove my_copy = my_list.copy() # copying the list i = 0 while i < len(my_copy): # while loop for iterating through the elements if my_copy[i] != char_to_delete: i += 1 else: my_copy.remove('b') # removing the char print(my_copy) # printing the updated list # ['a', 'a', 'e', 'a', 'e']
Notice the index i
is only incremented when the current character is not char_to_delete
.
Example 3: Remove All Occurrences with while Loop (Error Checking)
In Example 3, I’ll show how we can utilize the remove() function’s error output in our implementation. There are two possible outcomes of the remove() function:
- If the input value exists in the list, the first occurrence is removed, and nothing is returned.
- An error is returned if the input value doesn’t exist in the list.
We can utilize this behavior in our implementation. To do this, we will use a while loop with a condition initially set as check=False
, then we use a try-except block to try
executing the remove()
function and the except
block to terminate the while loop. The check
variable is set to True to terminate the loop.
char_to_delete = 'e' # assigning the char to remove my_copy = my_list.copy() # copying the list check = False while not check: try: my_copy.remove(char_to_delete) # removing the char except: check = True # error occurred, so loop condition 'check' is switched to True print(my_copy) # printing the updated list # ['a', 'b', 'a', 'b', 'a', 'b']
Example 4: Remove All Occurrences with filter() Function
Example 4 demonstrates how to utilize the filter() function. This function takes a user-defined function char_check()
and a list, then returns an iterator where only the elements which passed the check remain.
def char_check(char): char_to_delete = 'b' return char != char_to_delete my_copy = my_list.copy() # copying the list my_copy = list(filter(char_check, my_copy)) # filtering of the selected char print(my_copy) # printing the updated list # ['a', 'a', 'e', 'a', 'e']
Since the filter()
function returns an iterator, we need to convert it to a list via the list()
function. As seen, a list is printed with all the ‘b’ characters removed!
Video, Further Resources & Summary
I have recently released a video on my YouTube channel, which explains the examples of the present article. You can find the video below:
The YouTube video will be added soon.
Besides that, you may read the related articles on my homepage:
- Convert List from Character String to Float in Python
- Convert List from Character String to Integer in Python
- How to Clear All Elements in a List in Python
- All Python Programming Tutorials
- Convert List from Character String to Boolean in Python
To summarize: In this Python tutorial, you have learned how to delete all occurrences of a character. Don’t hesitate to let me know in the comments in case you have further questions. In addition, don’t forget to subscribe to my email newsletter to get regular updates on new tutorials.
This page was created in collaboration with Ömer Ekiz. Look at Ömer’s author page to get more information about his professional background, a list of all his tutorials, as well as an overview of his other tasks on Statistics Globe.
Statistics Globe Newsletter