Python | Remove given character from Strings list
Last Updated :
14 Apr, 2023
Sometimes, while working with Python list, we can have a problem in which we need to remove a particular character from each string from list. This kind of application can come in many domains. Let's discuss certain ways to solve this problem.
Method #1 : Using replace() + enumerate() + loop
This is brute force way in which this problem can be solved. In this, we iterate through each string and replace specified character with empty string to perform removal.
Step-by-step approach:
- Initialize a character named char which is to be removed from the strings in the list.
- Iterate over the list using a for loop and enumerate() function to get the index and corresponding element in each iteration.
- For each iteration, replace the character 's' with an empty string '' in the corresponding element using the replace() method and update the list with the modified element at the same index using the index obtained from enumerate().
- Print the modified list of strings.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Remove character from Strings list
# using loop + replace() + enumerate()
# initialize list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
# printing original list
print("The original list : " + str(test_list))
# initialize character
char = 's'
# Remove character from Strings list
# using loop + replace() + enumerate()
for idx, ele in enumerate(test_list):
test_list[idx] = ele.replace(char, '')
# printing result
print("The list after removal of character : " + str(test_list))
Output : The original list : ['gfg', 'is', 'best', 'for', 'geeks']
The list after removal of character : ['gfg', 'i', 'bet', 'for', 'geek']
Time complexity: O(n*m), where n is the length of the input list and m is the average length of the strings in the list.
Auxiliary space: O(1). The algorithm modifies the original list in place and does not create any new data structures.
Method #2: Using list comprehension + replace()
This task can also be performed using the above functionalities. In this, we offer a one-liner solution to this problem compacting the code using similar method as above.
Python3
# Python3 code to demonstrate working of
# Remove character from Strings list
# using list comprehension + replace()
# initialize list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
# printing original list
print("The original list : " + str(test_list))
# initialize character
char = 's'
# Remove character from Strings list
# using list comprehension + replace()
res = [ele.replace(char, '') for ele in test_list]
# printing result
print("The list after removal of character : " + str(res))
Output : The original list : ['gfg', 'is', 'best', 'for', 'geeks']
The list after removal of character : ['gfg', 'i', 'bet', 'for', 'geek']
Time complexity: O(n*m), where n is the length of the original list and m is the length of the longest string in the list
Auxiliary space: O(n*m).
Method #3: Using map(),lambda functions.
Python3
# Python3 code to demonstrate working of
# Remove character from Strings list
# using list comprehension + replace()
# initialize list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
# printing original list
print("The original list : " + str(test_list))
# initialize character
char = 's'
res = list(map(lambda x: x.replace(char, ''), test_list))
# printing result
print("The list after removal of character : " + str(res))
OutputThe original list : ['gfg', 'is', 'best', 'for', 'geeks']
The list after removal of character : ['gfg', 'i', 'bet', 'for', 'geek']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method#4: Using Recursive method.
Algorithm:
- Define a function to remove the character from the given list of strings.
- The function takes two inputs, the list of strings lst and the character to be removed char.
- Check if the list is empty. If yes, return an empty list.
- If the list is not empty, remove the character from the first string in the list using the replace method, and add it to a list.
- Recursively call the function with the rest of the list, and add the result to the list created in the previous step.
- Return the modified list of strings.
Python3
# Python3 code to demonstrate working of
# Remove character from Strings list
def remove_char(lst, char):
if not lst:
return []
else:
return [lst[0].replace(char, '')] + remove_char(lst[1:], char)
# initialize list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
# printing original list
print("The original list : " + str(test_list))
# initialize character
char = 's'
res =remove_char(test_list,char)
# printing result
print("The list after removal of character : " + str(res))
OutputThe original list : ['gfg', 'is', 'best', 'for', 'geeks']
The list after removal of character : ['gfg', 'i', 'bet', 'for', 'geek']
Time Complexity:
The time complexity of this function is O(n * m), where n is the number of strings in the list and m is the maximum length of any string in the list. This is because for each string, the replace method scans the entire string character by character, which takes up to m time. We need to perform this operation for each of the n strings in the list, resulting in a time complexity of O(n * m).
Auxiliary Space:
The space complexity of this function is O(n * m), where n is the number of strings in the list and m is the maximum length of any string in the list. This is because we create a new list to store the modified strings, and the size of each modified string could be up to m characters. We need to create this list for each of the n strings in the list, resulting in a space complexity of O(n * m).
Method #6: Using regex
- Import the re module.
- Define the function remove_char(lst, char) that takes a list of strings and a character as arguments.
- Use the re.sub() function to replace the specified character in each string in the list with an empty string.
- Return the modified list.
Python3
import re
def remove_char(lst, char):
return [re.sub(char, '', s) for s in lst]
# initialize list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
# printing original list
print("The original list : " + str(test_list))
# initialize character
char = 's'
res = remove_char(test_list,char)
# printing result
print("The list after removal of character : " + str(res))
OutputThe original list : ['gfg', 'is', 'best', 'for', 'geeks']
The list after removal of character : ['gfg', 'i', 'bet', 'for', 'geek']
Time complexity: O(nm), where n is the number of strings in the list and m is the average length of the strings. The re.sub() function has a time complexity of O(m) for each string in the list.
Auxiliary space: O(nm), where n is the number of strings in the list and m is the average length of the strings. This is the space required to store the modified strings in the new list.
Method #7: Using reduce():
Algorithm:
- Import the "reduce" function from the "functools" module and the "re" module for regular expressions.
- Define the "remove_char" function that takes a list of strings and a character as input.
- Use the "reduce" function to iterate over each string in the list and apply the "re.sub()" function to remove the specified character.
- Append the modified string to a new list.
- Return the new list with the modified strings.
- Initialize a list of strings "test_list".
- Print the original list.
- Initialize a character "char".
- Call the "remove_char" function with the "test_list" and "char" as arguments.
- Print the modified list.
Python3
from functools import reduce
import re
def remove_char(lst, char):
return reduce(lambda x, y: x + [re.sub(char, '', y)], lst, [])
# initialize list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
# printing original list
print("The original list : " + str(test_list))
# initialize character
char = 's'
res = remove_char(test_list,char)
# printing result
print("The list after removal of character : " + str(res))
#This code is contributed by Rayudu.
OutputThe original list : ['gfg', 'is', 'best', 'for', 'geeks']
The list after removal of character : ['gfg', 'i', 'bet', 'for', 'geek']
Time complexity:
The time complexity of the "remove_char" function is O(nm), where "n" is the length of the input list and "m" is the length of the longest string in the list. The "reduce" function takes O(n) time to iterate over each string in the list, and the "re.sub()" function takes O(m) time to remove the specified character from each string.
Space complexity:
The space complexity of the "remove_char" function is O(nm), where "n" is the length of the input list and "m" is the length of the longest string in the list. The function creates a new list to store the modified strings, which takes up O(nm) space.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read