4

I'm trying next code:

x = 'asd'
y = 'asd'
z = input() #write here string 'asd'. For Python 2.x use raw_input()
x == y # True.
x is y # True.
x == z # True.
x is z # False.

Why we have false in last expression?

Ivan Zelenskyy
  • 659
  • 9
  • 26
  • For small strings part: [`is` operator behaves differently when comparing strings with spaces](http://stackoverflow.com/questions/16756699/is-operator-behaves-differently-when-comparing-strings-with-spaces) – Ashwini Chaudhary Jan 31 '14 at 11:05
  • I don't think this is a duplicate. The title is misleading, but I think it is specifically about why the inputted string is not the same. It also does not contain a space, as in the other question. – tobias_k Jan 31 '14 at 11:09
  • 1
    The question may be slightly different, but the answers are the same-- `is` sometimes works, coincidentally, as an implementation detail in cpython. The fact that input is involved isn't particularly special; the takeaway should be to never use `is`. – Wooble Jan 31 '14 at 11:21
  • This is exactly what I came for – Bharat Aug 27 '17 at 13:18

2 Answers2

13

is checks for identity. a is b is True iff a and b are the same object (they are both stored in the same memory address).

== checks for equality, which is usually defined by the magic method __eq__ - i.e., a == b is True if a.__eq__(b) is True.

In your case specifically, Python optimizes the two hardcoded strings into the same object (since strings are immutable, there's no danger in that). Since input() will create a string at runtime, it can't do that optimization, so a new string object is created.

Amir Rachum
  • 76,817
  • 74
  • 166
  • 248
  • --input() will create a string at runtime x = 5 y = int(input()) # << 5 x == y #True x is y #True! But y is created at runtime too. – Ivan Zelenskyy Jan 31 '14 at 16:22
3

is checks not if the object are equal, but if the objects are actually the same object. Since input() always creates a new string, it never is another string.

Python creates one object for all occurrences of the same string literal, that's why x and y point to the same object.

Karol S
  • 9,028
  • 2
  • 32
  • 45