Check if the List in the Dictionary Is Empty in Python

This article will discuss four methods for checking if a list within a dictionary is empty. Before that, let’s briefly review how to access items in the Python dictionary as a prerequisite.

Accessing Elements of a Python Dictionary

Items of a Python dictionary can be accessed using the dictionary keys. This can be done using the square brackets or <dict>.get(<key>) function as shown below.

Output:

['Braeburn', 'Zetech', 'TUB', 'Yale', 'Warsaw']
['Braeburn', 'Zetech', 'TUB', 'Yale', 'Warsaw']
[3450, 2800, 4680, 6200, 5100]
[3450, 2800, 4680, 6200, 5100]

The main difference between the two methods: using <dict>[<key>] raises an error if the key being accessed does not exist, but <dict>.get(<key>) will return None.

Checking If the List within a Dictionary is Empty

This Section covers four methods for this purpose.

Method 1: Using if-statement

An empty list in Python is considered falsy. That means “if <list>” returns False if <list> is empty; otherwise, it returns True. Let’s see an example.

Output:

The list is empty.

Method 2: Using the bool() function

The bool(<obj>) evaluates the object passed to it as either True or False. If an empty list is passed, bool(<obj>) evaluates to False; otherwise, it evaluates to True. For example,

Output:

Check if empty (False if empty):  True
Check if empty (true if not empty):  False

Method 3: By checking its length

The length of a list can be determined using the inbuilt len() function. If the size of a list is zero, then it is effectively an empty list; otherwise, the length of the list is equal to the number of elements in it. For example,

With that in mind, we can now check if a list within a dictionary is empty using len() and if-statement, as shown below.

Output:

The list is not empty.
The list is empty.

Method 4: By comparing it to an empty list

We can also check if a list is empty by comparing it with a truly empty list using the comparison operator (==). If the list (say A) being checked is empty, then A==[ ] will return True; otherwise, it will return False.

Output:

The list is empty.
The list is not empty.

Conclusion

In this post, we learned four approaches to checking if a list within a dictionary is empty. The methods discussed include: using if-statement, checking the length of the list, using the bool() method, and comparing the list in question with an empty list.