Python: checking for an empty string


There are few tricks, that may do your Python code even faster. For example, the task of finding if a string is empty or not is not trivial as it seems. Would you like to find out?

Back in my Visual Basic childhood, checking for empty string was about checking it's length: Len(s) == 0.

Although, this approach works in Python, why not write it in clearer way?
1
2
3
4
5
6
7
SIZE = 10**6
t = 0
for i in range(0, SIZE):
    s = ''
    if s == '':
        t += 1
print(t)

According to cProfile, s == '' works 3x times faster than len(s) == 0. I suppose this is due to the fact that calling even built-in functions in Python is not as cheap as in compiled languages.

If you wonder, why not use the "not s construction, please read my article about comparing with None

Leave a comment

Introduce yourself:
Comment: BB-codes
Captcha:
captcha