Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Removing newline character from string in Python
Next article icon

Python | Remove given character from Strings list

Last Updated : 14 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  1. Initialize a character named char which is to be removed from the strings in the list.
  2. Iterate over the list using a for loop and enumerate() function to get the index and corresponding element in each iteration.
  3. 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().
  4. 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))
 
 
Output
The 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:

  1. Define a function to remove the character from the given list of strings.
  2. The function takes two inputs, the list of strings lst and the character to be removed char.
  3. Check if the list is empty. If yes, return an empty list.
  4. 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.
  5. Recursively call the function with the rest of the list, and add the result to the list created in the previous step.
  6. 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))
 
 
Output
The 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

  1. Import the re module.
  2. Define the function remove_char(lst, char) that takes a list of strings and a character as arguments.
  3. Use the re.sub() function to replace the specified character in each string in the list with an empty string.
  4. 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))
 
 
Output
The 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:

  1. Import the “reduce” function from the “functools” module and the “re” module for regular expressions.
  2. Define the “remove_char” function that takes a list of strings and a character as input.
  3. Use the “reduce” function to iterate over each string in the list and apply the “re.sub()” function to remove the specified character.
  4. Append the modified string to a new list.
  5. Return the new list with the modified strings.
  6. Initialize a list of strings “test_list”.
  7. Print the original list.
  8. Initialize a character “char”.
  9. Call the “remove_char” function with the “test_list” and “char” as arguments.
  10. 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.
 
 
Output
The 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.



Next Article
Removing newline character from string in Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python | Remove Kth character from strings list
    Sometimes, while working with data, we can have a problem in which we need to remove a particular column, i.e the Kth character from string list. String are immutable, hence removal just means re creating a string without the Kth character. Let's discuss certain ways in which this task can be perfor
    7 min read
  • Python - Remove Rear K characters from String List
    Sometimes, we come across an issue in which we require to delete the last characters from each string, that we might have added by mistake and we need to extend this to the whole list. This type of utility is common in web development. Having shorthands to perform this particular job is always a plu
    5 min read
  • Remove Multiple Characters from a String in Python
    Removing multiple characters from a string in Python can be achieved using various methods, such as str.replace(), regular expressions, or list comprehensions. Each method serves a specific use case, and the choice depends on your requirements. Let’s explore the different ways to achieve this in det
    3 min read
  • Removing newline character from string in Python
    When working with text data, newline characters (\n) are often encountered especially when reading from files or handling multi-line strings. These characters can interfere with data processing and formatting. In this article, we will explore different methods to remove newline characters from strin
    2 min read
  • Remove Duplicate Strings from a List in Python
    Removing duplicates helps in reducing redundancy and improving data consistency. In this article, we will explore various ways to do this. set() method converts the list into a set, which automatically removes duplicates because sets do not allow duplicate values. [GFGTABS] Python a = ["Learn
    3 min read
  • Python | Remove last character in list of strings
    Sometimes, we come across an issue in which we require to delete the last character from each string, that we might have added by mistake and we need to extend this to the whole list. This type of utility is common in web development. Having shorthands to perform this particular job is always a plus
    8 min read
  • Python | Remove List elements containing given String character
    Sometimes, while working with Python lists, we can have problem in which we need to perform the task of removing all the elements of list which contain at least one character of String. This can have application in day-day programming. Lets discuss certain ways in which this task can be performed. M
    7 min read
  • Python - Remove Non-English characters Strings from List
    Given a List of Strings, perform removal of all Strings with non-english characters. Input : test_list = ['Good| ????', '??Geeks???'] Output : [] Explanation : Both contain non-English characters Input : test_list = ["Gfg", "Best"] Output : ["Gfg", "Best"] Explanation : Both are valid English words.
    8 min read
  • Remove Special Characters from String in Python
    When working with text data in Python, it's common to encounter strings containing unwanted special characters such as punctuation, symbols or other non-alphanumeric elements. For example, given the input "Data!@Science#Rocks123", the desired output is "DataScienceRocks123". Let's explore different
    2 min read
  • Python | Return lowercase characters from given string
    Sometimes, while working with strings, we are concerned about the case sensitivity of strings and might require getting just a specific case of character in a long string. Let's discuss certain ways in which only lowercase letters can be extracted from a string. Method #1: Using list comprehension +
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences