About this question
I want to remove all empty strings from a list of strings in python.
My idea looks like this:
while '' in str_list:
str_list.remove('')
Is there any more pythonic way to remove empty strings from the list python?
I want to remove all empty strings from a list of strings in python.
My idea looks like this:
while '' in str_list:
str_list.remove('')
Is there any more pythonic way to remove empty strings from the list python?
Log in to share your answer and help other learners.
Log in to answerBest Answer · By JanBask Python Expert
Answered on Jun 9, 2021
There are many ways to remove empty strings from list python:
The first thing we can do is we can use filter() method to extract an empty string.
filter() construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container that supports iteration, or an iterator. If the function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.
We can use the following piece of code to that applies filter method:-
str_list = list(filter(None, str_list))
Another way of solving the above problem is by using List Comprehension.
Below is the code that illustrates the above mentioned method.
strings = ["abc", "", "efg"]
[x for x in strings if x]
Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.
Most-read guides across JanBask
Common Python interview questions, answered
Guides, tips and career advice on Python from JanBask experts.
Python How to Become a Python Developer: A Step-by-Step Guide for Beginners
Discover how to become a Python Developer via a practical 7-step guide build projects, maintain clean code, practice daily, and…
Python PCEP Certification Guide: Entry-Level Python Programmer Certification
Explore this PCEP certification guide for insights on cost, exam format, passing score, application, training, and study tips.…
Python Top 50+ Python Projects ideas for Beginners to Advanced
Discover innovative Python project ideas, explore advanced Python projects, and find good Python projects for beginners and…
Python How To Comment Out Multiple Lines In Python Like A Pro
Commenting out code is a common practice among programmers. It allows you to temporarily disable parts of your code without…