'is' returns False for equal strings
'is' returns False for equal strings in Python means `is` checks whether two names point to the same object; `==` checks whether the values are equal. Use == for strings and numbers.
How do I fix 'is' returns False for equal strings?
In Python, is checks whether two names point to the same object, while == checks whether the values are equal. Equal strings made in different ways, such as role.lower() and "admin", can be different objects, so is returns False. Use == for strings and numbers, and keep is for None, True and False.
- 1. Search for is with literalsLook for is "text" or is 1000. Python shows SyntaxWarning: "is" with 'str' literal for these.
- 2. Replace with ==Write if role.lower() == "admin": and if count == 1000: for value comparisons.
- 3. Keep is for Nonex is None, x is True and x is False are the correct uses of is.
What does 'is' returns False for equal strings mean?
Two strings with identical letters can be two different objects, for example one built by .lower() and one written as a literal. `is` then returns False even though == is True. It seems to work in quick tests because Python reuses some small strings and integers, which makes the bug intermittent. Python 3.8+ warns: SyntaxWarning: "is" with 'str' literal (3.12+ wording; 3.8 to 3.11 say "is" with a literal).
Why does 'is' returns False for equal strings happen?
1. Comparing strings with is
lower() returns a new string object.
Breaks
if role.lower() is "admin":Works
if role.lower() == "admin":2. Comparing numbers with is
Small ints are cached; large ones are not.
Breaks
if count is 1000:Works
if count == 1000:How to find it in your own code
Use == for every value comparison. Keep is for identity checks with singletons: x is None, x is True, x is False.
Practise logic errors
None of the challenges raises this exact error yet. These practise the same kind of bug.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.