Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which of these is the fastest way to check if a list is empty in Python? [duplicate]

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.

like image 441
mysl Avatar asked Nov 22 '25 15:11

mysl


1 Answers

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.

like image 146
Marat Avatar answered Nov 24 '25 05:11

Marat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!