Why is this string comparison returning False?

python, string

Solution

From the Python documentation:

The operators is and is not test for object identity: x is y is true if and only if x and y are the same object.

This means it doesn't check if the values are the same, but rather checks if they are in the same memory location. For example:

>>> s1 = 'hello everybody'
>>> s2 = 'hello everybody'
>>> s3 = s1

Note the different memory locations:

>>> id(s1)
174699248
>>> id(s2)
174699408

But since `s3` is equal to `s1`, the memory locations are the same:

>>> id(s3)
174699248

When you use the `is` statement:

>>> s1 is s2
False
>>> s3 is s1
True
>>> s3 is s2
False

But if you use the equality operator:

>>> s1 == s2
True
>>> s2 == s3
True
>>> s3 == s1
True

Edit: just to be confusing, there is an optimisation (in CPython anyway, I'm not sure if it exists in other implementations) which allows short strings to be compared with `is`:

>>> s4 = 'hello'
>>> s5 = 'hello'
>>> id(s4)
173899104
>>> id(s5)
173899104
>>> s4 is s5
True

Obviously, this is not something you want to rely on. Use the appropriate statement for the job - `is` if you want to compare identities, and `==` if you want to compare values.

Problem

Possible Duplicate: String comparison in Python: is vs. == ``` algorithm = str(sys.argv[1]) print(algorithm) print(algorithm is "first") ``` I'm running it from the command line with the argument `first`, so why does that code output: ``` first False ```

Original source

Related problems