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')

Output:

Advertisements
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.

Algorithm:

  • 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.
      • Else
        • Add bool to the bool list.
  • Then pass this bool list to any() to check if bool list contains any True value or not,
    • If yes
      • Then it confirms that our original list also contains an empty or blank list.
    • else
      • 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')

Output:

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()

Output:

*** 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

Pandas Tutorials -Learn Data Analysis with Python

   

Are you looking to make a career in Data Science with Python?

Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.

Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.

Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.

Join a LinkedIn Community of Python Developers

2 thoughts on “Python: Check if any string is empty in a list?”

  1. ”’ create an empty list named short_words ”’
    ”’ create an empty list named long_words ”’
    for x in range(10):
    ”’ input a string (use a prompt) and store it in a variable called word ”’
    ”’ Note: You must use an if-else statement. ”’
    ”’ if the word is 5 letters or less, append it to short_words,
    otherwise append it to long_words ”’
    # the loop is over, move all the way back to the left edge
    ”’ print a message that says how many short words there were ”’
    ”’ print the short_words list ”’
    ”’ print a message that says how many long words there were ”’
    ”’ print the long_words list ”’

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top