简体   繁体   中英

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

     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=['', '']

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

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, eg, 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

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)

To answer your first question about why a list of empty values is not considered empty, it's because it does contain something, even if those things are themselves empty. Think of it like a box of empty boxes.

The code below shows one way to modify the function foo() to do what you want (and test it). Your notion of what an empty list is was surprisingly tricky to devise, partially because it runs counter to what the language itself considers empty. As you can see all the logic dealing with the determination of whether the list is "empty" according to your definition has been moved into a separate function called empty_list() since that probably has little to do with the rest of what foo() has to accomplish. It's not overly complex and if nothing else should provide you with a good starting point.

Also, you didn't say what it should do if the argument it's passed isn't a list of any kind or was a list but didn't contain just other lists or strings, so as written it will raise a TypeError exception -- something which is similar to the way most built-in Python functions respond when this occurs with them. Below is the sample code and its test output:

try:
    string_type = basestring
except NameError: # probably Python 3.x
    string_type = str

class _NULL(object):  # unique marker object
    def __repr__(self): return '<nothing>'
_NULL = _NULL()

def empty_list(arg=_NULL):
    arg = arg if arg is not _NULL else []
    if not isinstance(arg, (list, string_type)):
        raise TypeError
    elif isinstance(arg, string_type):
        return not len(arg)
    else:
        return len(arg) == 0 or all(empty_list(e) for e in arg)

def foo(list_=None):
    if list_ is None or empty_list(list_):
        print 'list is empty'
    else:
        print 'list is not empty'

testcases = [
    _NULL,
    [],
    [''],
    ['', ''],
    ['', ['']],
    ['abc'],
    ['', 'abc'],
    [False],
    [None],
    [0],
    [0.0],
    [0L],
    [0j],
    [42],
    [{}],
    [{'':0}],
    [{'a':1}],
    False,
    None,
    0,
    0.0,
    0L,
    0j,
    42,
    {},
    {'':0},
    {'a':1},
]

for arg in testcases:
    call = 'foo( {!r:s} ) ->'.format(arg)
    print '{!s:>20s}'.format(call),
    try:
        foo() if arg is _NULL else foo(arg)
    except TypeError:
        print 'illegal argument exception'

Here's the output it produces with Python 2.7:

 foo( <nothing> ) -> list is empty
        foo( [] ) -> list is empty
      foo( [''] ) -> list is empty
  foo( ['', ''] ) -> list is empty
foo( ['', ['']] ) -> list is empty
   foo( ['abc'] ) -> list is not empty
foo( ['', 'abc'] ) -> list is not empty
   foo( [False] ) -> illegal argument exception
    foo( [None] ) -> illegal argument exception
       foo( [0] ) -> illegal argument exception
     foo( [0.0] ) -> illegal argument exception
      foo( [0L] ) -> illegal argument exception
      foo( [0j] ) -> illegal argument exception
      foo( [42] ) -> illegal argument exception
      foo( [{}] ) -> illegal argument exception
 foo( [{'': 0}] ) -> illegal argument exception
foo( [{'a': 1}] ) -> illegal argument exception
     foo( False ) -> illegal argument exception
      foo( None ) -> list is empty
         foo( 0 ) -> illegal argument exception
       foo( 0.0 ) -> illegal argument exception
        foo( 0L ) -> illegal argument exception
        foo( 0j ) -> illegal argument exception
        foo( 42 ) -> illegal argument exception
        foo( {} ) -> illegal argument exception
   foo( {'': 0} ) -> illegal argument exception
  foo( {'a': 1} ) -> illegal argument exception

The list [''] is, indeed, not empty. It contains an empty string. The string is empty, the list is not . If you want to find these lists, check if the list is empty, and if not, check if every entry is ''.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM