10

Is there any low-level, implementation-related difference (performance-ish) between these approaches..?

# check if string is empty
# the preferred way it seems [1]
if string:
    print string
else:
    print "It's empty."

# versus [2]
if string is '':

# or [3]
if string == '':

For example, when testing for None, I still find it more readable and explicit to do:

if some_var is not None:

..instead of..

if not some_var:

if not some_var, at least for me, always reads "if some_var does not exist".

Which is better to use, what are the proper use cases for ==, is and bool-testing?

3 Answers 3

8

Never use is for (value) equality testing. Only use it to test for object identity. It may work for the example if string is '', but this is implementation dependent, and you can't rely on it.

>>> a = "hi"
>>> a is "hi"
True
>>> a = "hi there!"
>>> a is "hi there!"
False

Other than that, use whatever conveys the meaning of your code best.

I prefer the shorter if string:, but if string != '': may be more explicit.

Then again if variable: works on every kind of object, so if variable isn't confined to one type, this is better than if variable != "" and variable != 0: etc.

Sign up to request clarification or add additional context in comments.

1 Comment

Great, thanks for the answer. And the "use whatever conveys the meaning of your code best" - this is a great thing to consider while coding, as well as when defending your solutions.
5

To expand on Tim Pietzcker's answer:

if string:
    print string

This tests if string evaluates to True. I.E.

>>> bool("")
False
>>> bool(None)
False
>>> bool("test")
True

So it's not only testing if it is empty, but if it is None or empty. This could have an impact depending on how you treat None/empty.

Comments

2

Firstly, don't use if string is '': because this is not guaranteed to work. The fact that CPython interns short strings is an implementation detail and should not be relied on.

Using if string: to check that string is non-empty is, I think, a Pythonic way to do it.

But there is nothing wrong about using if string == ''.

2 Comments

Alright, great. Could you expand on 'CPython interns short strings', or point me somewhere I could get more info?
... I feel ridiculous. Must've been half-asleep, forgot to jfGit. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.