- Python: Check if any string is empty in a list?
- Use any() and List Comprehension to check if list contains any empty string
- Frequently Asked:
- Check if list contains any empty string using for loop
- Related posts:
- Python – Create List of N Empty Strings
- Method 1: List Multiplication
- Method 2: List Comprehension
- Method 3: For Loop and append()
- Summary
- Programmer Humor
- Python One-Liners Book: Master the Single Line First!
- 4 Ways to Remove Empty Strings from a List
- Examples of removing empty strings from a list in Python
- Case 1: Using a list comprehension
- Case 2: Using for loop
- (3) Using filter:
- (4) Using filter and lambda:
Python: Check if any string is empty in a list?
In this article we will discuss different ways to check if a list contains any empty or blank string in python.
Use any() and List Comprehension to check if list contains any empty string
We have created a function to check if a string is empty. It will also consider a string empty if it contains only white spaces,
import re def is_empty_or_blank(msg): """ This function checks if given string is empty or contain only shite spaces""" return re.search("^\s*$", msg)
Now let’s use this function to check if a list contains any empty or blank string,
# Create a list of string list_of_str = ['11', 'This', 'is ', 'a', '', ' ', 'sample'] # Check if list contains any empty string or string with spaces only result = any([is_empty_or_blank(elem) for elem in list_of_str]) if result: print('Yes, list contains one or more empty strings') else: print('List does not contains any empty string')
Frequently Asked:
Yes, list contains one or more empty strings
It confirms that our list contains one or more empty / blank string.
Logic of this approach:
Using list comprehension, we created a bool list from our original list. If an element in bool list is True it means that corresponding element
in original list is an empty or blank string.
- First Create an empty bool list.
- Then iterate over each element in the list using list comprehension and for each element in the list,
- Check if it is empty or not using is_empty_or_blank() function.
- If element is an empty string,
- Then add True in the bool list.
- Add bool to the bool list.
- If yes
- Then it confirms that our original list also contains an empty or blank list.
- There is no empty/blank string in original list.
Check if list contains any empty string using for loop
Instead of using list comprehension, we can also implement the logic of previous solution using for loop i.e,
# Create a list of string list_of_str = ['11', 'This', 'is ', 'a', '', ' ', 'sample'] result = False # iterate over all the elements in list to check if list contains any empty string for elem in list_of_str: # Check if string is empty or contain only spaces if is_empty_or_blank(elem): result = True break; if result: print('Yes, list contains one or more empty string') else: print('List does not contains any empty string')
Yes, list contains one or more empty strings
It confirms that our list contains one or more empty or blank string.
Here we iterated over all elements of list and for each element we checked if it is an empty string or not. As soon as it encountered the first empty or blank string, it stopped checking the remaining elements. Whereas, if there are no empty strings in list, then it confirms only after check all elements in list.
The complete example is as follows,
import re def is_empty_or_blank(msg): """ This function checks if given string is empty or contain only shite spaces""" return re.search("^\s*$", msg) def main(): print('*** Check if list contains any empty string using list comprehension ***') # Create a list of string list_of_str = ['11', 'This', 'is ', 'a', '', ' ', 'sample'] # Check if list contains any empty string or string with spaces only result = any([is_empty_or_blank(elem) for elem in list_of_str]) if result: print('Yes, list contains one or more empty strings') else: print('List does not contains any empty string') print('*** Check if list contains any empty string using for loop ***') result = False # iterate over all the elements in list to check if list contains any empty string for elem in list_of_str: # Check if string is empty or contain only spaces if is_empty_or_blank(elem): result = True break; if result: print('Yes, list contains one or more empty string') else: print('List does not contains any empty string') if __name__ == '__main__': main()
*** Check if list contains any empty string using list comprehension *** Yes, list contains one or more empty strings *** Check if list contains any empty string using for loop *** Yes, list contains one or more empty string
Related posts:
Python – Create List of N Empty Strings
💬 Challenge: Given an integer n . How to create a list of n empty strings » in Python?
- Given n=0 . Create list [] .
- Given n=3 . Create list [», », »] .
- Given n=5 . Create list [», », », », »] .
Method 1: List Multiplication
You can create a list of n empty strings using the list concatenation (multiplication) operator on a list with one empty string using the expression [»] * n . This replicates the same identical empty string object to which all list elements refer. But as strings are immutable, this cannot cause any problems through aliasing.
def create_list_empty_strings(n): return [''] * n print(create_list_empty_strings(0)) # [] print(create_list_empty_strings(3)) # ['', '', ''] print(create_list_empty_strings(5)) # ['', '', '', '', '']
Method 2: List Comprehension
You can create a list of n empty strings by using list comprehension statement [» for _ in range(n)] that uses the range() function to repeat the creation and addition of an empty string n times.
def create_list_empty_strings(n): return ['' for _ in range(n)] print(create_list_empty_strings(0)) # [] print(create_list_empty_strings(3)) # ['', '', ''] print(create_list_empty_strings(5)) # ['', '', '', '', '']
Method 3: For Loop and append()
To create a list of n empty strings without special Python features, you can also create an empty list and use a simple for loop to add one empty string at a time using the list.append() method.
def create_list_empty_strings(n): my_list = [] for i in range(n): my_list.append('') return my_list print(create_list_empty_strings(0)) # [] print(create_list_empty_strings(3)) # ['', '', ''] print(create_list_empty_strings(5)) # ['', '', '', '', '']
Summary
There are three best ways to create a list with n empty strings.
- List concatenation [»] * n
- List comprehension [» for _ in range(n)]
- Simple for loop with list append(») on an initially empty list
Thanks for reading this article with Finxter! ❤️
Programmer Humor
❓ Question: How did the programmer die in the shower? ☠️
❗ Answer: They read the shampoo bottle instructions:
Lather. Rinse. Repeat.Python One-Liners Book: Master the Single Line First!
Python programmers will improve their computer science skills with these useful one-liners.
Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.
Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.
- Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
- Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
- Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
- Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
- Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.
Be on the Right Side of Change 🚀
- The world is changing exponentially. Disruptive technologies such as AI, crypto, and automation eliminate entire industries. 🤖
- Do you feel uncertain and afraid of being replaced by machines, leaving you without money, purpose, or value? Fear not! There a way to not merely survive but thrive in this new world!
- Finxter is here to help you stay ahead of the curve, so you can keep winning as paradigms shift.
Learning Resources 🧑💻
⭐ Boost your skills. Join our free email academy with daily emails teaching exponential with 1000+ tutorials on AI, data science, Python, freelancing, and Blockchain development!
Join the Finxter Academy and unlock access to premium courses 👑 to certify your skills in exponential technologies and programming.
New Finxter Tutorials:
Finxter Categories:
4 Ways to Remove Empty Strings from a List
Here are 4 ways to remove empty strings from a list in Python:
(1) Using a list comprehension:
new_list = [x for x in list_with_empty_strings if x != '']
(2) Using for loop:
new_list = [] for x in list_with_empty_strings: if x != '': new_list.append(x)
(3) Using filter:
new_list = list(filter(None, list_with_empty_strings))
(4) Using filter and lambda:
new_list = list(filter(lambda x: x != '', list_with_empty_strings))
Next, you’ll see how to apply each of the above approaches using simple examples.
Examples of removing empty strings from a list in Python
Case 1: Using a list comprehension
Suppose that you have the following list that contains empty strings:
list_with_empty_strings = ['blue', 'green', '', 'red', '', 'yellow', 'orange', ''] print(list_with_empty_strings)
As you can see, there are currently 3 empty strings in the list (as highlighted in yellow):
['blue', 'green', '', 'red', '', 'yellow', 'orange', '']
The goal is to remove those 3 empty strings from the list in Python.
You can then use a list comprehension to remove those empty strings:
list_with_empty_strings = ['blue', 'green', '', 'red', '', 'yellow', 'orange', ''] new_list = [x for x in list_with_empty_strings if x != ''] print(new_list)
The empty strings would now be removed:
['blue', 'green', 'red', 'yellow', 'orange']
Case 2: Using for loop
Alternatively, you can use a for loop to remove the empty strings:
list_with_empty_strings = ['blue', 'green', '', 'red', '', 'yellow', 'orange', ''] new_list = [] for x in list_with_empty_strings: if x != '': new_list.append(x) print(new_list)
You’ll get the same list without the empty strings:
['blue', 'green', 'red', 'yellow', 'orange']
(3) Using filter:
You can achieve the same results using a filter as follows:
list_with_empty_strings = ['blue', 'green', '', 'red', '', 'yellow', 'orange', ''] new_list = list(filter(None, list_with_empty_strings)) print(new_list)
As before, you’ll get the same list without the empty strings:
['blue', 'green', 'red', 'yellow', 'orange']
(4) Using filter and lambda:
Finally, you may apply a filter and lambda to remove the empty strings in the list:
list_with_empty_strings = ['blue', 'green', '', 'red', '', 'yellow', 'orange', ''] new_list = list(filter(lambda x: x != '', list_with_empty_strings)) print(new_list)
['blue', 'green', 'red', 'yellow', 'orange']
- If element is an empty string,
- Check if it is empty or not using is_empty_or_blank() function.