Python checking whether a list is empty
In Python, checking whether a list is empty is very simple. We can directly use if statement to check whether the list's length is 0, or directly check whether the list itself is False。
Example
my_list
=
[
]
Method 1: check whether the list length is 0
if
len
(
my_list
)
==
0
:
(
"The list is empty"
)
else
:
(
"The list is not empty"
)
Method 2: directly check whether the list is False
if
not
my_list:
(
"The list is empty"
)
else
:
(
"The list is not empty"
)
Code analysis:
len(my_list) == 0:len()function returns the length of the list; if the length is 0, the list is empty.not my_list: in Python, an empty list is treated asFalse, thereforenot my_listreturns when the list is emptyTrue。
Output result:
列表为空
列表为空
Both methods can effectively determine whether a list is empty; which one to use depends on personal preference.
Python3 Examples