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:
Replace Substrings from String List - Python
Next article icon

Python – Remove String from String List

Last Updated : 24 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

This particular article is indeed a very useful one for Machine Learning enthusiast as it solves a good problem for them. In Machine Learning we generally encounter this issue of getting a particular string in huge amount of data and handling that sometimes becomes a tedious task. Lets discuss certain way outs to solve this problem. 

Method #1: Using remove() This particular method is quite naive and not recommended to use, but is indeed a method to perform this task. remove() generally removes the first occurrence of K string and we keep iterating this process until no K string is found in list. 

Python3




# Python 3 code to demonstrate
# Remove K String from String List
# using remove()
 
# initializing list
test_list = ["bad", "GeeksforGeeks", "bad", "is", "best", "bad"]
 
# Printing original list
print("Original list is : " + str(test_list))
 
# initializing K
K = "bad"
 
# using remove() to
# Remove K String from String List
while(K in test_list):
    test_list.remove(K)
 
# Printing modified list
print("Modified list is : " + str(test_list))
 
 
Output : 
Original list is : ['bad', 'GeeksforGeeks', 'bad', 'is', 'best', 'bad'] Modified list is : ['GeeksforGeeks', 'is', 'best']

Time Complexity: O(n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1), constant extra space is required

Method #2: Using List Comprehension More concise and better approach to remove all the K strings, it just checks if the string is not K and re-makes the list with all strings that are not K. 

Python3




# Python 3 code to demonstrate
# Remove K String from String List
# using list comprehension
 
# initializing list
test_list = ["bad", "GeeksforGeeks", "bad", "is", "best", "bad"]
 
# Printing original list
print("Original list is : " + str(test_list))
 
# initializing K
K = "bad"
 
# using list comprehension to
# Remove K String from String List
test_list = [i for i in test_list if i != K]
 
# Printing modified list
print("Modified list is : " + str(test_list))
 
 
Output : 
Original list is : ['bad', 'GeeksforGeeks', 'bad', 'is', 'best', 'bad'] Modified list is : ['GeeksforGeeks', 'is', 'best']

Time Complexity: O(n)
Auxiliary Space: O(n), where n is length of list.

Method #3 : Using join(),replace(),split() and remove() methods

Python3




# Python 3 code to demonstrate
# Remove K String from String List
 
# initializing list
test_list = ["bad", "GeeksforGeeks", "bad", "is", "best", "bad"]
 
# Printing original list
print ("Original list is : " + str(test_list))
 
# initializing K
K = "bad"
 
x="-".join(test_list)
x=x.replace(K,"")
a=x.split("-")
while("" in a ):
    a.remove("")
# Printing modified list
print ("Modified list is : " + str(a))
 
 
Output
Original list is : ['bad', 'GeeksforGeeks', 'bad', 'is', 'best', 'bad'] Modified list is : ['GeeksforGeeks', 'is', 'best']

Here’s another approach to removing a string ‘K’ from a string list, using a filter:

Python




# Python 3 code to demonstrate
# Remove K String from String List
# using filter()
  
# initializing list
test_list = ["bad", "GeeksforGeeks", "bad", "is", "best", "bad"]
  
# Printing original list
print("Original list is : " + str(test_list))
  
# initializing K
K = "bad"
  
# using filter to Remove K String from String List
test_list = list(filter(lambda x: x!=K, test_list))
  
# Printing modified list
print("Modified list is : " + str(test_list))
 
 
Output
Original list is : ['bad', 'GeeksforGeeks', 'bad', 'is', 'best', 'bad'] Modified list is : ['GeeksforGeeks', 'is', 'best']

This approach uses the filter() function to create a filtered list of elements from test_list that are not equal to K. The list() function is then used to convert the filtered list into a list.

Time complexity: O(n), where n is the number of elements in the list test_list.

Space complexity: O(n), since a new list is created.



Next Article
Replace Substrings from String List - Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python - Remove substring list from String
    In Python Strings we encounter problems where we need to remove a substring from a string. However, in some cases, we need to handle a list of substrings to be removed, ensuring the string is adjusted accordingly. Using String Replace in a LoopThis method iterates through the list of substrings and
    3 min read
  • Python - Remove suffix from string list
    To remove a suffix from a list of strings, we identify and exclude elements that end with the specified suffix. This involves checking each string in the list and ensuring it doesn't have the unwanted suffix at the end, resulting in a list with only the desired elements. Using list comprehensionUsin
    3 min read
  • Replace Substrings from String List - Python
    The task of replacing substrings in a list of strings involves iterating through each string and substituting specific words with their corresponding replacements. For example, given a list a = ['GeeksforGeeks', 'And', 'Computer Science'] and replacements b = [['Geeks', 'Gks'], ['And', '&'], ['C
    3 min read
  • Python | Substring removal in String list
    While working with strings, one of the most used application is removing the part of string with another. Since string in itself is immutable, the knowledge of this utility in itself is quite useful. Here the removing of a substring in list of string is performed. Let’s discuss certain ways in which
    5 min read
  • Python - Remove after substring in String
    Removing everything after a specific substring in a string involves locating the substring and then extracting only the part of the string that precedes it. For example we are given a string s="Hello, this is a sample string" we need to remove the part of string after a particular substring includin
    3 min read
  • Python | Remove prefix strings from list
    Sometimes, while working with data, we can have a problem in which we need to filter the strings list in such a way that strings starting with a specific prefix are removed. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop + remove() + startswith() The combinati
    5 min read
  • Remove URLs from string in Python
    A regular expression (regex) is a sequence of characters that defines a search pattern in text. To remove URLs from a string in Python, you can either use regular expressions (regex) or some external libraries like urllib.parse. The re-module in Python is used for working with regular expressions. I
    3 min read
  • Python - Remove leading 0 from Strings List
    Sometimes, while working with Python, we can have a problem in which we have data which we need to perform processing and then pass the data forward. One way to process is to remove a stray 0 that may get attached to a string while data transfer. Let's discuss certain ways in which this task can be
    5 min read
  • Remove spaces from a string in Python
    Removing spaces from a string is a common task in Python that can be solved in multiple ways. For example, if we have a string like " g f g ", we might want the output to be "gfg" by removing all the spaces. Let's look at different methods to do so: Using replace() methodTo remove all spaces from a
    2 min read
  • Python | Removing Initial word from string
    During programming, sometimes, we can have such a problem in which it is required that the first word from the string has to be removed. These kinds of problems are common and one should be aware about the solution to such problems. Let's discuss certain ways in which this problem can be solved. Met
    4 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