Rolex Pearlmaster Replica
  Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
This article is part of in the series
Published: Tuesday 19th March 2013
Last Updated: Wednesday 29th December 2021

The preferred way to check if any list, dictionary, set, string or tuple is empty in Python is to simply use an if statement to check it.

For example, if we define a function as such:

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

It will magically detect if any built in structure is empty. So if we run this:

[python]
>>> 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
[/python]

Then, if we add something to each:

[python]
>>> d['element'] = 42
>>> l.append('element')
>>> ms.add('element')
>>> s = 'string'
>>> t = ('element')
[/python]

And we check each one again, this will be the result:

[python]
>>>is_empty(d)
Structure is not empty.
False
[/python]

As you can see, all the default data structures are detected as empty by treating the structure like a boolean in the if statement.

If the data structure is empty, it "returns" False when used in a boolean context. If the data structure has elements, it "returns" True when used in a boolean context.

One thing to note is that "empty" keys that have values in dictionaries will still be counted as "non-empty". For example:

[python]
>>> d = {None:'value'}
>>> is_empty(d)
Structure is not empty.
False
[/python]

This is because even though the key is "empty", it still counts as an entry in the dictionary, which means it's not empty.

"Is it really that simple? Do I have to do anything else?", I hear you say.

Yes, it is that simple. Python is amazing. Deal with it. 🙂

How NOT to Check if a List, Tuple, or Dictionary is Empty

"So what if I want to use a different way to check if these structures are empty?", you say.

Well, most other ways aren't "wrong", they're just not the Python way of doing things. For example, if you wanted to check if a structure was empty by using Python's len function, that would not be considered Pythonic.

For example, you could use this way to check if a list is empty:

[python]
if len(l) == 0:
print('Empty!')
[/python]

Now, this is most certainly not wrong, but why would you type all that extra code? When something is labeled "Pythonic", it is usually referring to Python's nature of being very terse. So if you can save space by making your code shorter, that is usually the more Pythonic way of doing things.

The way above would probably be labeled as the "C" way of doing things, because it looks a lot like C code.

That's all for this article!

Until we meet again.

About The Author

Joey Payne

Latest Articles


Tags

  • Parsing
  • tail
  • merge sort
  • Programming language
  • remove python
  • concatenate string
  • Code Editors
  • unittest
  • reset_index()
  • Train Test Split
  • Local Testing Server
  • Python Input
  • Studio
  • excel
  • sgd
  • deeplearning
  • pandas
  • class python
  • intersection
  • logic
  • pydub
  • git
  • Scrapping
  • priority queue
  • quick sort
  • web development
  • uninstall python
  • python string
  • code interface
  • PyUnit
  • round numbers
  • train_test_split()
  • Flask module
  • Software
  • FL
  • llm
  • data science
  • testing
  • pathlib
  • oop
  • gui
  • visualization
  • audio edit
  • requests
  • stack
  • min heap
  • Linked List
  • machine learning
  • scripts
  • compare string
  • time delay
  • PythonZip
  • pandas dataframes
  • arange() method
  • SQLAlchemy
  • Activator
  • Music
  • AI
  • ML
  • import
  • file
  • jinja
  • pysimplegui
  • notebook
  • decouple
  • queue
  • heapify
  • Singly Linked List
  • intro
  • python scripts
  • learning python
  • python bugs
  • ZipFunction
  • plus equals
  • np.linspace
  • SQLAlchemy advance
  • Download
  • No
  • nlp
  • machiine learning
  • dask
  • file management
  • jinja2
  • ui
  • tdqm
  • configuration
  • deque
  • heap
  • Data Structure
  • howto
  • dict
  • csv in python
  • logging in python
  • Python Counter
  • python subprocess
  • numpy module
  • Python code generators
  • KMS
  • Office
  • modules
  • web scraping
  • scalable
  • pipx
  • templates
  • python not
  • pytesseract
  • env
  • push
  • search
  • Node
  • python tutorial
  • dictionary
  • csv file python
  • python logging
  • Counter class
  • Python assert
  • linspace
  • numbers_list
  • Tool
  • Key
  • automation
  • website data
  • autoscale
  • packages
  • snusbase
  • boolean
  • ocr
  • pyside6
  • pop
  • binary search
  • Insert Node
  • Python tips
  • python dictionary
  • Python's Built-in CSV Library
  • logging APIs
  • Constructing Counters
  • Assertions
  • Matplotlib Plotting
  • any() Function
  • Activation
  • Patch
  • threading
  • scrapy
  • game analysis
  • dependencies
  • security
  • not operation
  • pdf
  • build gui
  • dequeue
  • linear search
  • Add Node
  • Python tools
  • function
  • python update
  • logging module
  • Concatenate Data Frames
  • python comments
  • matplotlib
  • Recursion Limit
  • License
  • Pirated
  • square root
  • website extract python
  • steamspy
  • processing
  • cybersecurity
  • variable
  • image processing
  • incrementing
  • Data structures
  • algorithm
  • Print Node
  • installation
  • python function
  • pandas installation
  • Zen of Python
  • concatenation
  • Echo Client
  • Pygame
  • NumPy Pad()
  • Unlock
  • Bypass
  • pytorch
  • zipp
  • steam
  • multiprocessing
  • type hinting
  • global
  • argh
  • c vs python
  • Python
  • stacks
  • Sort
  • algorithms
  • install python
  • Scopes
  • how to install pandas
  • Philosophy of Programming
  • concat() function
  • Socket State
  • % Operator
  • Python YAML
  • Crack
  • Reddit
  • lightning
  • zip files
  • python reduce
  • library
  • dynamic
  • local
  • command line
  • define function
  • Pickle
  • enqueue
  • ascending
  • remove a node
  • Django
  • function scope
  • Tuple in Python
  • pandas groupby
  • pyenv
  • socket programming
  • Python Modulo
  • Dictionary Update()
  • Hack
  • sdk
  • python automation
  • main
  • reduce
  • typing
  • ord
  • print
  • network
  • matplotlib inline
  • Pickling
  • datastructure
  • bubble sort
  • find a node
  • Flask
  • calling function
  • tuple
  • GroupBy method
  • Pythonbrew
  • Np.Arange()
  • Modulo Operator
  • Python Or Operator
  • Keygen
  • cloud
  • pyautogui
  • python main
  • reduce function
  • type hints
  • python ord
  • format
  • python socket
  • jupyter
  • Unpickling
  • array
  • sorting
  • reversal
  • Python salaries
  • list sort
  • Pip
  • .groupby()
  • pyenv global
  • NumPy arrays
  • Modulo
  • OpenCV
  • Torrent
  • data
  • int function
  • file conversion
  • calculus
  • python typing
  • encryption
  • strings
  • big o calculator
  • gamin
  • HTML
  • list
  • insertion sort
  • in place reversal
  • learn python
  • String
  • python packages
  • FastAPI
  • argparse
  • zeros() function
  • AWS Lambda
  • Scikit Learn
  • Free
  • classes
  • turtle
  • convert file
  • abs()
  • python do while
  • set operations
  • data visualization
  • efficient coding
  • data analysis
  • HTML Parser
  • circular queue
  • effiiciency
  • Learning
  • windows
  • reverse
  • Python IDE
  • python maps
  • dataframes
  • Num Py Zeros
  • Python Lists
  • Fprintf
  • Version
  • immutable
  • python turtle
  • pandoc
  • semantic kernel
  • do while
  • set
  • tabulate
  • optimize code
  • object oriented
  • HTML Extraction
  • head
  • selection sort
  • Programming
  • install python on windows
  • reverse string
  • python Code Editors
  • Pytest
  • pandas.reset_index
  • NumPy
  • Infinite Numbers in Python
  • Python Readlines()
  • Trial
  • youtube
  • interactive
  • deep
  • kernel
  • while loop
  • union
  • tutorials
  • audio
  • github
  • Python is a beautiful language.