How To Check If Element In List Is Empty In Python
Check one item or an entire Python list for None, empty strings and other empty values using is, any() and clear generator expressions.
The clearest way to check whether a particular list element is None is to use is None:
values = [None, 2, 3]
if values[0] is None:
print("The first item is None")
Use is None, rather than == None, because None is a single special object in Python. The is operator checks that identity directly.
Check whether a list contains None
Use any() with a generator expression when you need to inspect the entire list:
values = [1, 2, None, 4]
contains_none = any(item is None for item in values)
print(contains_none) # True
any() stops as soon as it finds a match. It also avoids creating the temporary list that a list comprehension would produce.
If you only need a membership test, this shorter form is also clear:
contains_none = None in values
Decide what “empty” means
Python does not have one definition of an empty list element. You may be looking for one of several values:
| Value | Recommended check |
|---|---|
None | item is None |
| Empty string | item == "" |
| Empty list | item == [] |
| Any falsy value | not item |
Be careful with not item: it treats None, False, 0, empty strings and empty containers as empty. Use it only when all of those values should count.
values = ["ready", "", 0, None]
contains_falsy_value = any(not item for item in values)
print(contains_falsy_value) # True
Find the empty elements
If you need the positions rather than a True or False answer, collect the indexes with enumerate():
values = ["ready", None, "done", None]
empty_indexes = [
index
for index, item in enumerate(values)
if item is None
]
print(empty_indexes) # [1, 3]
Quick reference
- Check one position:
values[index] is None - Check the whole list:
any(item is None for item in values) - Check membership:
None in values - Find matching positions: use
enumerate()in a list comprehension
Next, see how to check whether a list itself is empty or add an empty element to a list.