consider this simple function
def foo(l=[]):
if not l: print "List is empty"
else : print "List is not empty"
Now let's call foo
x=[]
foo(x)
#List is empty
foo('')
#List is empty
But if x=[''] the list is not considered as empty!!!
x=['']
foo(x)
#List is not empty
Questions -
Why list of empty values are not considered as empty? (In case of variable it is considered as empty e.g.)
x=''
if x:print 'not empty!!'
else: print 'empty'
How can I modify function foo() so that list will be considered as empty in all these cases: x=[]
, x=['']
, x=['', '']
Using the built-in any()
def foo(l=[]):
if any(l):
print 'List is not empty'
else:
print 'List is empty'
foo([''])
# List is empty
In your examples, the only case where the list really is empty is the one in which there is nothing in the square brackets. In the other examples you have lists with various numbers of empty strings. These are simply different (and in all languages I can think of, the same would be true).
You can use recursive call to the function foo to deal with nested lists.
def foo(l=[]):
if type(l)==list:
return any([foo(x) for x in l])
else:
return bool(l)
First of all: Even an empty string is a string. A list that contains an empty string still contains an element.
while a=''
is empty with len = 0, it is regardless for the list, it still contains an element, e.g., mylist = [a]
is the same as mylist = ['']
but it might be clearer to you. Take a
as an element and ignore the content.
To check if elements of a list are empty, iterate over them.
def isEmpty(li=[]):
for elem in li:
if len(elem) > 0: return false
return true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With