3

Before getting to the main question, I should first ask: When you're trying to check if a list is empty in Python, is there any case where the four cases below would yield a different boolean?

  1. if not []
  2. if not len([])
  3. if len([]) == 0
  4. if len([]) is 0

If not, which is the fastest way to check for this boolean and why? - i.e. what exactly is happening under the hood for each case? The difference may be trivial but I'm curious as to how these might differ during execution.

mysl
  • 1,003
  • 2
  • 9
  • 19
  • 1
    Definitely don't pick `is`. Two equal ints are not guaranteed to be the same object. – user2357112 May 21 '20 at 22:55
  • 1
    Also if you mean lists, use the word "list". Even if they behave like data types other languages call "array", it's important to use the correct terminology for the language, because "array" refers to other things in Python. – user2357112 May 21 '20 at 22:56
  • @user2357112supportsMonica Could you share a case where two equal ints wouldn't be the same object? I'm still fairly new to programming! – mysl May 21 '20 at 23:11
  • @mysl: https://ideone.com/EvYZVt – user2357112 May 21 '20 at 23:24
  • 1
    @mysl the python interpreter has already loaded in memory numbers between -5 and 256, so if you use those numbers equal numbers might refer to the same object, but if you use other numbers equal numbers might not refer to the same object: eg: >>> a = 400 >>> b = 400 >>> a is b False >>> a = 200 >>> b = 200 >>> a is b True – Hoxha Alban May 21 '20 at 23:28

1 Answers1

2

if not array

This is the most idiomatic way to check it. Caveat: it will not work on other iterables, e.g. numpy arrays.

if not len(array)

Equivalent to the expression above, but is not as idiomatic. It will work on numpy arrays, but still might fail on other iterables with custom __len__ (nonexistent threat, to be clear)

if len(array) == 0

Same as above, but eliminates the nonexistent threat from custom iterables

if len(array) is 0

DANGER ZONE: it will work in CPython because of implementation details, but generally there is no guarantee it won't break in the future, or that it'll work on other Python implementations. Avoid at all costs.

Marat
  • 15,215
  • 2
  • 39
  • 48
  • Where can I find the guarantees what wont break in the future (or what will work) – lalala May 22 '20 at 05:38
  • @lalala Backward incompatible changes can be introduced only in major releases, i.e. in Python 4. Things that are not in specification can be changed any moment. So, current implementation of CPython has special behavior for ints from -5 to slightly over 100, but it is not part of the specification, just a speedup trick. Things like these are implementation dependent and can change – Marat May 22 '20 at 12:24