Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python checking whether a list is empty

Python checking whether a list is empty

Document Object Reference Manual Python3 Examples

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

:

   

print

(

"The list is empty"

)

else

:

   

print

(

"The list is not empty"

)

Method 2: directly check whether the list is False

if

not

my_list:

   

print

(

"The list is empty"

)

else

:

   

print

(

"The list is not empty"

)

Code analysis:

  1. len(my_list) == 0:len() function returns the length of the list; if the length is 0, the list is empty.
  2. not my_list: in Python, an empty list is treated as False, therefore not my_list returns when the list is empty True。

Output result:

列表为空
列表为空

Both methods can effectively determine whether a list is empty; which one to use depends on personal preference.

Document Object Reference Manual Python3 Examples