60
Python Performance: Why 'if not list' is 2x Faster Than Using len()
(blog.codingconfessions.com)
Welcome to the Python community on the programming.dev Lemmy instance!
Past
November 2023
October 2023
July 2023
August 2023
September 2023
The notion of truthiness is defined by the language.
It's not something that happens to work, it's literally defined that way.
if not x
is the common way to tell if you have data or not, and in most cases, the difference betweenNone
and empty data ([]
,{}
, etc) isn't important.len(x) == 0
will raise an exception if you give itNone
, and that's usually not what you want. So I guess the verbose way to do that isif x is None or len(x) == 0:
, but that's exactly equivalent toif not x
, with the small caveat that it doesn't check if the value has__len__
implemented. If you're getting wonky types thrown around (i.e. getting a class instance when expecting a list), you have bigger problems.I use type hinting on pretty much all "public" methods and functions, and many of my "private" methods and functions as well. As such, sending the wrong types is incredibly unlikely, so
not x
is more than sufficient and clearly indicates intent (do I have data?).I did not say it's not semantically well defined.
https://en.wikipedia.org/wiki/Brainfuck#Hello_World! -- this is semantically well defined, but it's still vague. Vagueness is a property of how well the syntax is conveying intent.
It's only vague if coming from a language where it's invalid or vague semantically. For example:
[]
is truthy for whatever reasonint x[] = {};
evaluates to true because it's a pointer; C only evaluates to false if something is 0nil
orfalse
The only surprising one here is Javascript. I argue Lua and Python make sense for the same reason, Lua just decided to evaluate truthiness based on whether the variable is set, whereas Python decided to evaluate it based on the contents of the variable. I prefer the Python approach here, but I prefer Lua as a language generally (love the simplicity).