Python Performance: Why 'if not list' is 2x Faster Than Using len()

https://lemmy.world/post/28121911

Python Performance: Why 'if not list' is 2x Faster Than Using len() - Lemmy.World

Lemmy

Yea and then you use “not” with a variable name that does not make it obvious that it is a list and another person who reads the code thinks it is a bool. Hell a couple of months later you yourself wont even understand that it is a list. You should not sacrifice code readability for over optimization, this is phyton after all I don’t think list lengths will be your bottle neck.
Strongly disagree that not x implies to programmers that x is a bool.

Doesn’t matter what it implies. The entire purpose of programming is to make it so a human doesn’t have to go do something manually.

not x tells me I need to go manually check what type x is in Python.

len(x) == 0 tells me that it’s being type-checked automatically

That’s just not true:

  • not x - has an empty value (None, False, [], {}, etc)
  • len(x) == 0 - has a length (list, dict, tuple, etc, or even a custom type implementing __len__)

You can probably assume it’s iterable, but that’s about it.

But why assume? You can easily just document the type with a type-hint:

def do_work(foo: list | None): if not foo: return ...