Python check empty list
This article will explore different ways to check if list is empty in python with example programs.
Python len() function is used to find the length of a list or the number of elements in it.
For empty list,
len()will return 0. So, to check if list is empty or not, compare the return value with 0 as shown below.
l =  if len(l) == 0: print('List is empty')
Comparison with 0 can be skipped when using
len(). So, above code can be shortened to
l =  if len(l): print('List is empty')
PEP(Python Enhancement Proposal) 8 does not recommend this syntax.
Method 2: Checking empty sequence
PEP 8 states that empty sequences(strings, lists or tuples) are
False. So, empty list is
False and non-empty list is
Below syntax checks if a list is empty in python
l =  if not l: print('List is empty')
not before empty list makes it
True, so the
if test passes.
This syntax is recommended by PEP 8.
To check for non-empty list, use below code
l =  if l: print('List is not empty')
Compare the list to be checked with an empty list using
If the list to check is empty, it will return
Trueas shown below
list_to_check =  empty_list =  if list_to_check == empty_list: print('List is empty')
That is all on different ways to check if list is empty in python. Hope the article was helpful.1