"is" vs "=="

When to use what and how to use it. (a dilemma for newbies)

If you are reading this, you may have faced this confusion at least once. All python beginners(sometimes intermediate too) face this dilemma and confusion.

The == operator compares the value of two variables, and the is keyword checks whether two variables point to the same address. You should use the == in most cases, except when you’re comparing to the None datatype.

Examples

Let's say you want to compare the value of a variable to another.

name = "john"

if name is "john":
    print(True)
else:
    print(False)

# you end up getting a SyntaxWarning and a suggestion (python 3.8)
#>>> SyntaxWarning: "is" with a literal. Did you mean "=="?

The better way to write it will be:

if name == "john":
    print(True)
else:
    print(False)

>>> True

Conclusion

In many cases, and as an advice to beginners, pretend the is keyword doesn't exist until when you need it.

Bonus Resources