Although, in a boolean context, an empty list ([]
) and None
are both falsy values, they're not the same:
# in a boolean context, `[]` and `None` are falsy
print(bool([]) == bool(None)) # True
# `[]` and `None` are not equivalent
print([] == None) # False
In Python, None
is a special constant that indicates the absence of a value, while an empty list represents a list with no elements.
To highlight their distinctions, consider the following examples:
def foo():
# this function implicitly returns `None`
pass
result = foo()
print(result) # None
In the code above, the function "foo()
" does not explicitly return a value, so it implicitly returns None
. In contrast, the creation of an empty list is denoted by square brackets ([]
):
empty_list = []
print(empty_list) # []
As you can see, an empty list does not have any elements. You can verify this by checking the length of the list by using the len()
function:
list_size = len([])
print(list_size) # 0
That being said, the list can have one (or more) "None
" elements, in which case, the size of the list will increase:
list_size = len([None])
print(list_size) # 1
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.