In my experience, if you didn’t write the function that creates the list, there’s a solid chance it could be None too, and if you try to check the length of None, you get an error. This is also why returning None when a function fails is bad practice IMO, but that doesn’t seem to stop my coworkers.
Sometimes there’s an important difference between None and []. That’s by far not the most common use, but it does exist (e.g. None could mean “user didn’t supply any data” and [] could mean “user explicitly supplied empty data”).
If the distinction matters, make it explicit:
if foo isNone:
raise ValueError("foo must be defined for this operation")
ifnot foo:
returnNonefor bar in foo:
...
return some_other_value
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 foo can probably just return None or use some default value or whatever, and whether it’s None or [] doesn’t matter.
iflen(foo)== 0: is bad for a few reasons:
TypeError will be raised if it’s None, which is probably unexpected
it’s slower
it’s longer
If you don’t care about the distinction, handle both the same way. If you do care, handle them separately.
In my experience, if you didn’t write the function that creates the list, there’s a solid chance it could be
None
too, and if you try to check the length ofNone
, you get an error. This is also why returningNone
when a function fails is bad practice IMO, but that doesn’t seem to stop my coworkers.Passing None to a function expecting a list is the error…
good point I try to initialize None collections to empty collections in the beginning but not always guaranteed and len would catch it
Sometimes there’s an important difference between
None
and[]
. That’s by far not the most common use, but it does exist (e.g.None
could mean “user didn’t supply any data” and[]
could mean “user explicitly supplied empty data”).If the distinction matters, make it explicit:
if foo is None: raise ValueError("foo must be defined for this operation") if not foo: return None for bar in foo: ... return some_other_value
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 foo
can probably just returnNone
or use some default value or whatever, and whether it’sNone
or[]
doesn’t matter.if len(foo) == 0:
is bad for a few reasons:TypeError
will 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.