Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python how to check list does't contain any value

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 -

  1. 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'
    
  2. How can I modify function foo() so that list will be considered as empty in all these cases: x=[] , x=[''], x=['', '']

like image 358
d.putto Avatar asked Jun 25 '12 14:06

d.putto


4 Answers

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
like image 60
Christian Witts Avatar answered Sep 21 '22 13:09

Christian Witts


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).

like image 38
Alex Wilson Avatar answered Sep 22 '22 13:09

Alex Wilson


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)
like image 31
Imrul Avatar answered Sep 22 '22 13:09

Imrul


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
like image 28
tuergeist Avatar answered Sep 18 '22 13:09

tuergeist