Comment on Python Performance: Why 'if not list' is 2x Faster Than Using len()
iAvicenna@lemmy.world 7 months agogood point I try to initialize None collections to empty collections in the beginning but not guaranteed and len would catch it
Comment on Python Performance: Why 'if not list' is 2x Faster Than Using len()
iAvicenna@lemmy.world 7 months agogood point I try to initialize None collections to empty collections in the beginning but not guaranteed and len would catch it
sugar_in_your_tea@sh.itjust.works 7 months ago
Sometimes there’s an important difference between
Noneand[]. That’s by far not the most common use, but it does exist (e.g.Nonecould mean “user didn’t supply any data” and[]could mean “user explicitly supplied empty data”).If the distinction matters, make it explicit:
This way you’re explicit about what constitutes an error vs no data, and the caller can differentiate as well. In most cases though, you don’t need that first check,
if not foocan probably just returnNoneor use some default value or whatever, and whether it’sNoneor[]doesn’t matter.if len(foo) == 0:is bad for a few reasons:TypeErrorwill be raised if it’sNone, which is probably unexpectedIf you don’t care about the distinction, handle both the same way. If you do care, handle them separately.