Generalized empty checking in python

Hi there, everybody. It’s been a while.

At this post, I put an example about how simple is to check “emptyness” of any structure in Python. I’ve found by looking a way to do it… in let’s say.. in pythonic way, because I’m familiar with structured programming with C which is little less flexible than Python.

So, the example below is from here.

General function to check if a data structure is empty:

def is_empty(any_structure):
    if any_structure:
        print('Structure is not empty.')
        return False
    else:
        print('Structure is empty.')
        return True

You’re gonna see somethin like this:

>>> d = {}     # Empty dictionary
>>> l = []     # Empty list
>>> ms = set() # Empty set
>>> s = ''     # Empty string
>>> t = ()     # Empty tuple
>>> is_empty(d)
Structure is empty.
True
>>> is_empty(l)
Structure is empty.
True
>>> is_empty(ms)
Structure is empty.
True
>>> is_empty(d)
Structure is empty.
True
>>> is_empty(s)
Structure is empty.
True
>>> is_empty(t)
Structure is empty.
True
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s