The former can handle both empty string and None
. For example consider these two variables.
>>> s1 = ''
>>> s2 = None
Using the first method
def test(s):
if s:
return True
else:
return False
>>> test(s1)
False
>>> test(s2)
False
Now using len
def test(s):
if len(s) == 0:
return True
else:
return False
>>> test(s1)
True
>>> test(s2)
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
test(s2)
File "<pyshell#11>", line 2, in test
if len(s) == 0:
TypeError: object of type 'NoneType' has no len()
So in terms of performance, both will be O(1), but the truthiness test (the first method) is more robust in that it handles None
in addition to empty strings.