csdnceshi79
python小菜
采纳率0%
2008-09-10 06:20 阅读 968

如何检查列表是否为空?

For example, if passed the following:

a = []

How do I check to see if a is empty?

转载于:https://stackoverflow.com/questions/53513/how-do-i-check-if-a-list-is-empty

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

30条回答 默认 最新

  • 已采纳
    csdnceshi54 hurriedly% 2008-09-10 06:28
    if not a:
      print("List is empty")
    

    Using the implicit booleanness of the empty list is quite pythonic.

    点赞 20 评论 复制链接分享
  • csdnceshi65 larry*wei 2008-09-10 10:33

    The pythonic way to do it is from the PEP 8 style guide (where Yes means “recommended” and No means “not recommended”):

    For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

    Yes: if not seq:
         if seq:
    
    No:  if len(seq):
         if not len(seq):
    
    点赞 30 评论 复制链接分享
  • csdnceshi57 perhaps? 2008-09-10 06:31

    An empty list is itself considered false in true value testing (see python documentation):

    a = []
    if a:
         print "not empty"
    

    @Daren Thomas

    EDIT: Another point against testing the empty list as False: What about polymorphism? You shouldn't depend on a list being a list. It should just quack like a duck - how are you going to get your duckCollection to quack ''False'' when it has no elements?

    Your duckCollection should implement __nonzero__ or __len__ so the if a: will work without problems.

    点赞 29 评论 复制链接分享
  • weixin_41568134 MAO-EYE 2012-02-21 16:48

    Other people seem to be generalizing the question beyond just lists, so I thought I'd add a caveat for a different type of sequence that a lot of people might use, especially since this is the first google hit for "python test empty array".

    Other methods don't work for numpy arrays

    You need to be careful with numpy arrays, because other methods that work fine for lists or other standard containers fail for numpy arrays. I explain why below, but in short, the preferred method is to use size.

    The "pythonic" way doesn't work: Part 1

    The "pythonic" way fails with numpy arrays because numpy tries to cast the array to an array of bools, and if x tries to evaluate all of those bools at once for some kind of aggregate truth value. But this doesn't make any sense, so you get a ValueError:

    >>> x = numpy.array([0,1])
    >>> if x: print("x")
    ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
    

    The "pythonic" way doesn't work: Part 2

    But at least the case above tells you that it failed. If you happen to have a numpy array with exactly one element, the if statement will "work", in the sense that you don't get an error. However, if that one element happens to be 0 (or 0.0, or false, ...), the if statement will incorrectly result in false:

    >>> x = numpy.array([0,])
    >>> if x: print("x")
    ... else: print("No x")
    No x
    

    But clearly x exists and is not empty! This result is not what you wanted.

    Using len can give unexpected results

    For example,

    len( numpy.zeros((1,0)) )
    

    returns 1, even though the array has zero elements.

    The numpythonic way

    As explained in the scipy FAQ, the correct method in all cases where you know you have a numpy array is to use if x.size:

    >>> x = numpy.array([0,1])
    >>> if x.size: print("x")
    x
    
    >>> x = numpy.array([0,])
    >>> if x.size: print("x")
    ... else: print("No x")
    x
    
    >>> x = numpy.zeros((1,0))
    >>> if x.size: print("x")
    ... else: print("No x")
    No x
    

    If you're not sure whether it might be a list, a numpy array, or something else, you could combine this approach with the answer @dubiousjim gives to make sure the right test is used for each type. Not very "pythonic", but it turns out that numpy intentionally broke pythonicity in at least this sense.

    If you need to do more than just check if the input is empty, and you're using other numpy features like indexing or math operations, it's probably more efficient (and certainly more common) to force the input to be a numpy array. There are a few nice functions for doing this quickly — most importantly numpy.asarray. This takes your input, does nothing if it's already an array, or wraps your input into an array if it's a list, tuple, etc., and optionally converts it to your chosen dtype. So it's very quick whenever it can be, and it ensures that you just get to assume the input is a numpy array. We usually even just use the same name, as the conversion to an array won't make it back outside of the current scope:

    x = numpy.asarray(x, dtype=numpy.double)
    

    This will make the x.size check work in all cases I see on this page.

    点赞 24 评论 复制链接分享
  • csdnceshi66 必承其重 | 欲带皇冠 2011-09-05 00:30

    I prefer it explicitly:

    if len(li) == 0:
        print('the list is empty')
    

    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.

    点赞 21 评论 复制链接分享
  • csdnceshi72 谁还没个明天 2017-03-29 02:58

    Being inspired by @dubiousjim's solution, I propose to use an additional general check of whether is it something iterable

    import collections
    def is_empty(a):
        return not a and isinstance(a, collections.Iterable)
    

    Note: a string is considered to be iterable. - add and not isinstance(a,(str,unicode)) if you want the empty string to be excluded

    Test:

    >>> is_empty('sss')
    False
    >>> is_empty(555)
    False
    >>> is_empty(0)
    False
    >>> is_empty('')
    True
    >>> is_empty([3])
    False
    >>> is_empty([])
    True
    >>> is_empty({})
    True
    >>> is_empty(())
    True
    
    点赞 10 评论 复制链接分享
  • weixin_41568183 零零乙 2012-06-02 15:40

    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.

    点赞 9 评论 复制链接分享
  • csdnceshi78 程序go 2016-04-13 21:55
    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])
    

    produces expected

    list is empty
    list is empty
    list has 3 elements
    
    点赞 8 评论 复制链接分享
  • csdnceshi68 local-host 2012-05-31 14:35

    I had written:

    if isinstance(a, (list, some, other, types, i, accept)) and not a:
        do_stuff
    

    which was voted -1. I'm not sure if that's because readers objected to the strategy or thought the answer wasn't helpful as presented. I'll pretend it was the latter, since---whatever counts as "pythonic"---this is the correct strategy. Unless you've already ruled out, or are prepared to handle cases where a is, for example, False, you need a test more restrictive than just if not a:. You could use something like this:

    if isinstance(a, numpy.ndarray) and not a.size:
        do_stuff
    elif isinstance(a, collections.Sized) and not a:
        do_stuff
    

    the first test is in response to @Mike's answer, above. The third line could also be replaced with:

    elif isinstance(a, (list, tuple)) and not a:
    

    if you only want to accept instances of particular types (and their subtypes), or with:

    elif isinstance(a, (list, tuple)) and not len(a):
    

    You can get away without the explicit type check, but only if the surrounding context already assures you that a is a value of the types you're prepared to handle, or if you're sure that types you're not prepared to handle are going to raise errors (e.g., a TypeError if you call len on a value for which it's undefined) that you're prepared to handle. In general, the "pythonic" conventions seem to go this last way. Squeeze it like a duck and let it raise a DuckError if it doesn't know how to quack. You still have to think about what type assumptions you're making, though, and whether the cases you're not prepared to handle properly really are going to error out in the right places. The Numpy arrays are a good example where just blindly relying on len or the boolean typecast may not do precisely what you're expecting.

    点赞 7 评论 复制链接分享
  • csdnceshi59 ℙℕℤℝ 2016-01-01 18:18

    From documentation on truth value testing:

    All values other than what is listed here are considered True

    • None
    • False
    • zero of any numeric type, for example, 0, 0.0, 0j.
    • any empty sequence, for example, '', (), [].
    • any empty mapping, for example, {}.
    • instances of user-defined classes, if the class defines a __bool__() or __len__() method, when that method returns the integer zero or bool value False.

    As can be seen, empty list [] is falsy, so doing what would be done to a boolean value sounds most efficient:

    if not a:
        print('"a" is empty!')
    
    点赞 7 评论 复制链接分享
  • csdnceshi72 谁还没个明天 2018-03-19 11:14

    Another simple way could be

    a = []
    if len(a) == 0:
      print("Empty")
    else:
      print(" Not empty")
    
    点赞 7 评论 复制链接分享
  • csdnceshi58 Didn"t forge 2014-12-03 02:21

    Patrick's (accepted) answer is right: if not a: is the right way to do it. Harley Holcombe's answer is right that this is in the PEP 8 style guide. But what none of the answers explain is why it's a good idea to follow the idiom—even if you personally find it's not explicit enough or confusing to Ruby users or whatever.

    Python code, and the Python community, has very strong idioms. Following those idioms makes your code easier to read for anyone experienced in Python. And when you violate those idioms, that's a strong signal.

    It's true that if not a: doesn't distinguish empty lists from None, or numeric 0, or empty tuples, or empty user-created collection types, or empty user-created not-quite-collection types, or single-element NumPy array acting as scalars with falsey values, etc. And sometimes it's important to be explicit about that. And in that case, you know what you want to be explicit about, so you can test for exactly that. For example, if not a and a is not None: means "anything falsey except None", while if len(a) != 0: means "only empty sequences—and anything besides a sequence is an error here", and so on. Besides testing for exactly what you want to test, this also signals to the reader that this test is important.

    But when you don't have anything to be explicit about, anything other than if not a: is misleading the reader. You're signaling something as important when it isn't. (You may also be making the code less flexible, or slower, or whatever, but that's all less important.) And if you habitually mislead the reader like this, then when you do need to make a distinction, it's going to pass unnoticed because you've been "crying wolf" all over your code.

    点赞 6 评论 复制链接分享
  • weixin_41568134 MAO-EYE 2015-10-06 19:25

    Why check at all?

    No one seems to have addressed questioning your need to test the list in the first place. Because you provided no additional context, I can imagine that you may not need to do this check in the first place, but are unfamiliar with list processing in Python.

    I would argue that the most pythonic way is to not check at all, but rather to just process the list. That way it will do the right thing whether empty or full.

    a = []
    
    for item in a:
        <do something with item>
    
    <rest of code>
    

    This has the benefit of handling any contents of a, while not requiring a specific check for emptiness. If a is empty, the dependent block will not execute and the interpreter will fall through to the next line.

    If you do actually need to check the array for emptiness, the other answers are sufficient.

    点赞 6 评论 复制链接分享
  • csdnceshi52 妄徒之命 2008-09-15 05:50

    len() is an O(1) operation for Python lists, strings, dicts, and sets. Python internally keeps track of the number of elements in these containers.

    JavaScript has a similar notion of truthy/falsy.

    点赞 5 评论 复制链接分享
  • weixin_41568208 北城已荒凉 2016-09-13 11:53

    You can even try using bool() like this

        a = [1,2,3];
        print bool(a); # it will return True
        a = [];
        print bool(a); # it will return False
    

    I love this way for checking list is empty or not.

    Very handy and useful.

    点赞 5 评论 复制链接分享
  • weixin_41568174 from.. 2016-11-28 14:18

    Here are a few ways you can check if a list is empty:

    a = [] #the list
    

    1) The pretty simple pythonic way:

    if not a:
        print("a is empty")
    

    In Python, empty containers such as lists,tuples,sets,dicts,variables etc are seen as False. One could simply treat the list as a predicate (returning a Boolean value). And a True value would indicate that it's non-empty.

    2) A much explicit way: using the len() to find the length and check if it equals to 0:

    if len(a) == 0:
        print("a is empty")
    

    3) Or comparing it to an anonymous empty list:

    if a == []:
        print("a is empty")
    

    4) Another yet silly way to do is using exception and iter():

    try:
        next(iter(a))
        # list has elements
    except StopIteration:
        print("Error: a is empty")
    
    点赞 5 评论 复制链接分享
  • weixin_41568208 北城已荒凉 2018-10-12 04:01

    Many answers have been given, and a lot of them are pretty good. I just wanted to add that the check

    not a
    

    will also pass for None and other types of empty structures. If you truly want to check for an empty list, you can do this:

    if isinstance(a, list) and len(a)==0:
        print("Received an empty list")
    
    点赞 4 评论 复制链接分享
  • csdnceshi55 ~Onlooker 2018-10-12 02:59

    Simple way is checking the length is equal zero.

    if len(a) == 0:
        print("a is empty")
    
    点赞 3 评论 复制链接分享
  • csdnceshi59 ℙℕℤℝ 2014-10-27 00:35

    Some methods that I use:

    if not a:
        print "list is empty"
    
    
    if len(a) == 0:
        print "list is empty"
    
    点赞 2 评论 复制链接分享
  • csdnceshi64 游.程 2008-09-10 06:28

    I have seen the below as preferred:

    if not a:
        print("The list is empty or null")
    
    点赞 1 评论 复制链接分享
  • csdnceshi62 csdnceshi62 2008-09-10 06:43

    I prefer the following:

    if a == []:
       print "The list is empty."
    

    Readable and you don't have to worry about calling a function like len() to iterate through the variable. Although I'm not entirely sure what the BigO notation of something like this is... but Python's so blazingly fast I doubt it'd matter unless a was gigantic.

    点赞 1 评论 复制链接分享
  • csdnceshi71 Memor.の 2017-08-20 03:50

    Best way to check if a list is empty

    For example, if passed the following:

    a = []
    

    How do I check to see if a is empty?

    Short Answer:

    Place the list in a boolean context (for example, with an if or while statement). It will test False if it is empty, and True otherwise. For example:

    if not a:                           # do this!
        print('a is an empty list')
    

    Appeal to Authority

    PEP 8, the official Python style guide for Python code in Python's standard library, asserts:

    For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

    Yes: if not seq:
         if seq:
    
    No: if len(seq):
        if not len(seq):
    

    We should expect that standard library code should be as performant and correct as possible. But why is that the case, and why do we need this guidance?

    Explanation

    I frequently see code like this from experienced programmers new to Python:

    if len(a) == 0:                     # Don't do this!
        print('a is an empty list')
    

    And users of lazy languages may be tempted to do this:

    if a == []:                         # Don't do this!
        print('a is an empty list')
    

    These are correct in their respective other languages. And this is even semantically correct in Python.

    But we consider it un-Pythonic because Python supports these semantics directly in the list object's interface via boolean coercion.

    From the docs (and note specifically the inclusion of the empty list, []):

    By default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero, when called with the object. Here are most of the built-in objects considered false:

    • constants defined to be false: None and False.
    • zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
    • empty sequences and collections: '', (), [], {}, set(), range(0)

    And the datamodel documentation:

    object.__bool__(self)

    Called to implement truth value testing and the built-in operation bool(); should return False or True. When this method is not defined, __len__() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__() nor __bool__(), all its instances are considered true.

    and

    object.__len__(self)

    Called to implement the built-in function len(). Should return the length of the object, an integer >= 0. Also, an object that doesn’t define a __bool__() method and whose __len__() method returns zero is considered to be false in a Boolean context.

    So instead of this:

    if len(a) == 0:                     # Don't do this!
        print('a is an empty list')
    

    or this:

    if a == []:                     # Don't do this!
        print('a is an empty list')
    

    Do this:

    if not a:
        print('a is an empty list')
    

    Doing what's Pythonic usually pays off in performance:

    Does it pay off? (Note that less time to perform an equivalent operation is better:)

    >>> import timeit
    >>> min(timeit.repeat(lambda: len([]) == 0, repeat=100))
    0.13775854044661884
    >>> min(timeit.repeat(lambda: [] == [], repeat=100))
    0.0984637276455409
    >>> min(timeit.repeat(lambda: not [], repeat=100))
    0.07878462291455435
    

    For scale, here's the cost of calling the function and constructing and returning an empty list, which you might subtract from the costs of the emptiness checks used above:

    >>> min(timeit.repeat(lambda: [], repeat=100))
    0.07074015751817342
    

    We see that either checking for length with the builtin function len compared to 0 or checking against an empty list is much less performant than using the builtin syntax of the language as documented.

    Why?

    For the len(a) == 0 check:

    First Python has to check the globals to see if len is shadowed.

    Then it must call the function, load 0, and do the equality comparison in Python (instead of with C):

    >>> import dis
    >>> dis.dis(lambda: len([]) == 0)
      1           0 LOAD_GLOBAL              0 (len)
                  2 BUILD_LIST               0
                  4 CALL_FUNCTION            1
                  6 LOAD_CONST               1 (0)
                  8 COMPARE_OP               2 (==)
                 10 RETURN_VALUE
    

    And for the [] == [] it has to build an unnecessary list and then, again, do the comparison operation in Python's virtual machine (as opposed to C)

    >>> dis.dis(lambda: [] == [])
      1           0 BUILD_LIST               0
                  2 BUILD_LIST               0
                  4 COMPARE_OP               2 (==)
                  6 RETURN_VALUE
    

    The "Pythonic" way is a much simpler and faster check since the length of the list is cached in the object instance header:

    >>> dis.dis(lambda: not [])
      1           0 BUILD_LIST               0
                  2 UNARY_NOT
                  4 RETURN_VALUE
    

    Evidence from the C source and documentation

    PyVarObject

    This is an extension of PyObject that adds the ob_size field. This is only used for objects that have some notion of length. This type does not often appear in the Python/C API. It corresponds to the fields defined by the expansion of the PyObject_VAR_HEAD macro.

    From the c source in Include/listobject.h:

    typedef struct {
        PyObject_VAR_HEAD
        /* Vector of pointers to list elements.  list[0] is ob_item[0], etc. */
        PyObject **ob_item;
    
        /* ob_item contains space for 'allocated' elements.  The number
         * currently in use is ob_size.
         * Invariants:
         *     0 <= ob_size <= allocated
         *     len(list) == ob_size
    

    I have enjoyed researching this and I spend a lot of time curating my answers. If you think I'm leaving something out, please let me know in a comment.

    点赞 1 评论 复制链接分享
  • csdnceshi56 lrony* 2017-08-26 19:04

    Simply use is_empty() or make function like:-

    def is_empty(any_structure):
        if any_structure:
            print('Structure is not empty.')
            return True
        else:
            print('Structure is empty.')
            return False  
    

    It can be used for any data_structure like a list,tuples, dictionary and many more. By these, you can call it many times using just is_empty(any_structure).

    点赞 评论 复制链接分享
  • weixin_41568184 叼花硬汉 2017-12-09 14:57

    An unofficial approach :

     a = []
     try:
      print(a[-1])
     except IndexError:
      print("List is empty")
    
    点赞 评论 复制链接分享
  • csdnceshi76 斗士狗 2017-12-14 18:31

    i think people suggested for

    if len(list1) == 0:
        print("is a good way")
    

    or len you can count by

    if list1.__ len__()==0:
        print("list1 is empty")
    

    you can use one more way

    if list1.__ sizeof__() == 40:
        print("list1 is empty")
    

    size of empty list is always 40.

    点赞 评论 复制链接分享
  • csdnceshi69 YaoRaoLov 2017-12-27 09:28

    Look at the following code executed on Python interactive terminal.

    >>> a = []
    >>> if a:
    ...     print "List is not empty";
    ... else:
    ...     print "List is empty"
    ... 
    List is empty
    >>> 
    >>> a = [1, 4, 9]
    >>> if a:
    ...     print "List is not empty";
    ... else:
    ...     print "List is empty"
    ... 
    List is not empty
    >>> 
    
    点赞 评论 复制链接分享
  • csdnceshi50 三生石@ 2018-03-05 11:30

    If you want to check if list is empty;

    l = []
    if l:
        # do your stuff.
    

    If you want to check weather all the values in list is empty.

    l = ["", False, 0, '', [], {}, ()]
    if all(bool(x) for x in l):
        # do your stuff.
    

    However this will be True for empty list.

    def empty_list(lst):
        if len(lst) ==0:
            return false
        else:
            return all(bool(x) for x in l)
    

    Now you can use:

    if empty_list(lst):
        # do your stuff.
    
    点赞 评论 复制链接分享
  • csdnceshi73 喵-见缝插针 2018-05-16 04:13

    The truth value of an empty list is False whereas for a non-empty list it is True.

    点赞 评论 复制链接分享
  • weixin_41568131 10.24 2018-10-31 13:05

    Collection.Any() always returns false if list is empty

    点赞 评论 复制链接分享
  • weixin_41568127 ?yb? 2018-11-03 02:23
    print('not empty' if a else 'empty')
    

    a little more practical:

    a.pop() if a else None
    
    点赞 评论 复制链接分享

相关推荐