5

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
Community
  • 1
  • 1
temporary_user_name
  • 35,956
  • 47
  • 141
  • 220
  • other duplicate: http://stackoverflow.com/questions/1504717/why-does-comparing-strings-in-python-using-either-or-is-sometimes-produce – 0 _ Sep 10 '14 at 21:16

3 Answers3

13

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.

Blair
  • 15,356
  • 7
  • 46
  • 56
6

You want:

algorithm = str(sys.argv[1])
print(algorithm)
print(algorithm == "first")

is checks for object identity (think memory address). But in your case the the objects have the same "value", but are not the same objects.

Note that == is weaker than is. This means that if is returns True, then == will also return True, but the reverse is not always true.

Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95
  • `==` tests if the comparands have the same value, `is` tests if they have the same `id` (roughly equivalent to memory location). – Sam Mussmann Dec 08 '12 at 22:12
  • 1
    From a devil's advocate POV feel free to explain why `a = 'a'; b='a'; a is b"` is true – Jon Clements Dec 08 '12 at 22:25
  • In python ascii strings of size 1 (well and 0 of course) are stored internally and then shared among variables, like integers. So `a` and `b` are pointing to the same place in memory and therefore identical – Dmitry Shevchenko Dec 09 '12 at 03:15
3

Basically, is checks object's address (identity), not value,. For value comparison use == operator

Dmitry Shevchenko
  • 31,814
  • 10
  • 56
  • 62