In this article, we will discuss different ways to remove a character from a list of strings in python.

Suppose we have a list of strings,

list_of_str = ['what', 'why', 'now', 'where', 'who', 'how', 'wow']

Now, we want to remove all occurrences of character ‘w’ rom this list of strings. After that list should be like this,

['hat', 'hy', 'no', 'here', 'ho', 'ho', 'o']

There are different ways to do this. Let’s discuss them one by one,

Remove a character from list of strings using list comprehension and replace()

Strings are immutable in python, so we can not modify them in place. But we can create a new string with the modified contents. So create a new list with the modified strings and then assign it back to the original variable.

For that, use the list comprehension to iterate over all strings in the list. Then for each string, call the replace() function to replace all occurrences of the character to be deleted with an empty string. Finally list comprehension will return a new list of modified strings. Let’s see it in working code,

list_of_str = ['what', 'why', 'now', 'where', 'who', 'how', 'wow']

ch = 'w'
# Remove character 'w' from the list of strings
list_of_str = [elem.replace(ch, '') for elem in list_of_str]

print(list_of_str)

Output:

['hat', 'hy', 'no', 'here', 'ho', 'ho', 'o']

It deleted all occurrences of character ‘w’ from the list of strings.

Remove a character from list of strings using map() function

We can also use the map() function to remove a character from all the strings in a list. Steps are as follows,

  • Create a lambda function, that accepts a string and returns a copy of the string after removing the given character from it.
  • Pass the lambda function and the list of strings as arguments to the map() function.
  • map() function will iterate over all string in the list and call the lambda function on it. Which returns a new string after removing the giving character. Finally map() function returns mapped object containing modified strings.
  • Pass the mapped object to the list() to create a new list of strings.
  • This strings in list do not contain the given character. So, eventually we deleted a given character from the list of strings.

Working example is as follows,

list_of_str = ['what', 'why', 'now', 'where', 'who', 'how', 'wow']

# Remove character 'w' from the list of strings
list_of_str  = list(map(lambda elem: elem.replace(ch, ''), list_of_str))

print(list_of_str)

Output:

['hat', 'hy', 'no', 'here', 'ho', 'ho', 'o']

It deleted all occurrences of character ‘w’ from the list of strings.

Summary:

We learned about two different ways to delete a character from a list of strings in python.