def list_test (L):
if L is None : print 'list is None'
elif not L : print 'list is empty'
else: print 'list has %d elements' % len(L)
list_test(None)
list_test([])
list_test([1,2,3])
It is sometimes good to test for None and for emptiness separately as those are two different states. The code above produces the following output:
list is None
list is empty
list has 3 elements
Although it's worth nothing that None is falsy. So if you don't want to separate test for None-ness, you don't have to do that.
def list_test2 (L):
if not L : print 'list is empty'
else: print 'list has %d elements' % len(L)
list_test2(None)
list_test2([])
list_test2([1,2,3])
This way it's 100% clear that li is a sequence (list) and we want to test its size. My problem with if not li: ... is that it gives the false impression that li is a boolean variable.
Python is very uniform about the treatment of emptiness. Given the following:
a = []
.
.
.
if a:
print("List is not empty.")
else:
print("List is empty.")
You simply check list a with an "if" statement to see if it is empty. From what I have read and been taught, this is the "Pythonic" way to see if a list or tuple is empty.
To check whether a list is empty or not you can use two following ways. But remember, we should avoid the way of explicitly checking for a sequence or list (it's a less pythonic way):
def Enquiry(list1):
if len(list1) == 0:
return 0
else:
return 1
# ––––––––––––––––––––––––––––––––
list1 = []
if Enquiry(list1):
print ("The list isn't empty")
else:
print("The list is Empty")
# Result: "The list is Empty".
The second way is a more pythonic one. This method is an implicit way of checking and much more preferable than the previous one.
def Enquiry(list1):
if not list1:
return 1
else:
return 0
# ––––––––––––––––––––––––––––––––
list1 = []
if Enquiry(list1):
print ("The list is Empty")
else:
print ("The list isn't empty")
# Result: "The list is Empty"
It is sometimes good to test for
None
and for emptiness separately as those are two different states. The code above produces the following output:Although it's worth nothing that
None
is falsy. So if you don't want to separate test forNone
-ness, you don't have to do that.produces expected
I prefer it explicitly:
This way it's 100% clear that
li
is a sequence (list) and we want to test its size. My problem withif not li: ...
is that it gives the false impression thatli
is a boolean variable.Python is very uniform about the treatment of emptiness. Given the following:
You simply check list a with an "if" statement to see if it is empty. From what I have read and been taught, this is the "Pythonic" way to see if a list or tuple is empty.
Hope this helps.
If you want to check if list is empty;
If you want to check weather all the values in list is empty.
However this will be True for empty list.
Now you can use:
Some methods that I use: