Categories
list python

How do I check if a list is empty?

3231

For example, if passed the following:

a = []

How do I check to see if a is empty?

0

    6823

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

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

    31

    • 1430

      Playing devil’s advocate. I don’t understand why this idiom is considered pythonic. ‘Explicit is better then implicit’, correct? This check doesn’t seem very explicit about what is is checking.

      Nov 22, 2011 at 6:14


    • 267

      @JamesMcMahon – it’s a trade-off between explicitness and type flexibility. generally, “being explicit” means not doing “magical” things. on the other hand, “duck typing” means working with more general interfaces, rather than explicitly checking for types. so something like if a == [] is forcing a particular type (() == [] is False). here, general consensus seems to be that duck typing wins out (in effect, saying that __nonzero__ is the interface for testing emptiness docs.python.org/reference/datamodel.html#object.__nonzero__)

      May 31, 2012 at 14:50

    • 101

      This method doesn’t work on numpy arrays.. so I think if len(a) == 0 is preferable both in terms of “duck typing” and implicitness.

      Mar 20, 2019 at 18:01

    • 22

      The canonical way of knowing if an array in C is empty is by dereferencing the first element and seeing if it is null, assuming an array that is nul-terminated. Otherwise, comparing its length to zero is utterly inefficient if the array is of a significant size. Also, typically, you would not allocate memory for an empty array (pointer remains null), so it makes no sense to attempt to get its length. I am not saying that len(a) == 0 is not a good way of doing it, it just does not scream ‘C’ to me when I see it.

      – sleblanc

      Apr 2, 2019 at 23:55

    • 71

      Coming from a language that claims to be some sort of poetry, this mechanism is pure garbage. Semantically, being empty is very different to not being

      Apr 4, 2020 at 14:03

    1416

    The pythonic way to do it is from the PEP 8 style guide.

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

    # Correct:
    if not seq:
    if seq:
    
    # Wrong:
    if len(seq):
    if not len(seq):
    

    9

    • 104

      The second way seems better if you wish to signal that seq is expected to be some sort of list-like object.

      May 10, 2018 at 18:44

    • 19

      @BallpointBen which, Pythonism advocates would say, should be implicit in the way the variable is named, as much as possible

      – axolotl

      Jul 14, 2018 at 5:35

    • 13

      @BallpointBen try using Python’s type hinting for signaling what a variable should be. It was introduced in 3.5.

      Jan 4, 2019 at 23:46

    • 16

      numpy broke this idiom… seq = numpy.array([1,2,3]) followed by if not seq raises an exception “ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()”

      Mar 20, 2019 at 18:03

    • 10

      Despite all Pythonic advocates, I am with @BallpointBen in that if you mistakenly wrote seq = [0] as seq = 0, len(seq) will help you catch the error. To err is human. So is a programmer.

      – aafulei

      Sep 26, 2019 at 2:34

    1010

    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.

    22

    • 131

      Checking if the length of a list is equal to zero, rather than just checking if the list is false, is ugly and unpythonic. Anyone familiar with Python will not think li is a bool at all, and wont care. If it’s important, you should add a comment, not more code.

      Jul 9, 2013 at 13:43


    • 32

      This seems like an unnecessarily precise test, which is often slower and is always less readable IMHO. Instead of checking the size of something empty, why not just check if it’s empty?

      – John B

      Jun 23, 2014 at 14:46


    • 48

      Anyway, the reason this is bad (and that violating idioms in a language with strong idioms like Python is bad in general) is that it signals to the reader that you’re specifically checking the length for some reason (e.g., because you want None or 0 to raise an exception rather than passing). So, when you do it for no reason, that’s misleading—and it also means that when your code does need to make the distinction, the distinction is invisible because you’ve “cried wolf” all over the rest of the source.

      – abarnert

      Dec 3, 2014 at 2:05

    • 30

      I think this is just needlessly lengthening the code. Otherwise, why not be even more “explicit” with if bool(len(li) == 0) is True:?

      – augurar

      Jan 5, 2015 at 19:40

    • 17

      @Jabba it will be O(1) in many cases (those where you work with the built-in data types), but you just can’t rely on that. You might be working with a custom data type that doesn’t have this property. You might also decide to add this custom data type later, after you already wrote this code.

      – ralokt

      Nov 19, 2015 at 13:04