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

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

Python Performance: Why 'if not list' is 2x Faster Than Using len()
Python Performance: Why 'if not list' is 2x Faster Than Using len()
Could also compare against:
if not len(mylist)
That way this version isn’t evaluating two functions. The bool evaluation of an integer is false when zero, otherwise true.
That's worse. IMO, solve this problem with two things:
mylist
as list | None
or just list
if not mylist:
The first documents intent and gives you static analysis tools some context to check for type consistency/compatibility, and the second shows that None
vs empty isn't an important distinction here.
This is honestly the worst version regarding readability. Don't rely on implicit coercion, people.
But the first example does the same thing for an empty list. I guess the lesson is that if you’re measuring the speed of arbitrary stylistic syntax choices, maybe Python isn’t the best language for you.
Yes, the first example does the same thing, but there's still less to mentally parse. Ideally you should just use if len(mylist) == 0:
.