abhi9u@lemmy.world to Technology@lemmy.worldEnglish · 4 days agoPython Performance: Why 'if not list' is 2x Faster Than Using len()blog.codingconfessions.comexternal-linkmessage-square150fedilinkarrow-up1219arrow-down124
arrow-up1195arrow-down1external-linkPython Performance: Why 'if not list' is 2x Faster Than Using len()blog.codingconfessions.comabhi9u@lemmy.world to Technology@lemmy.worldEnglish · 4 days agomessage-square150fedilink
minus-squaresugar_in_your_tea@sh.itjust.workslinkfedilinkEnglisharrow-up1·3 days agoThat’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 ...
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 ...