2

Why is this:

x = str(input("Enter a string: "))       #input "cat"
y = str(input("Enter another string: ")) #input "cat"
print(x is y) #Outputs False

Not the same as this:

x = "cat"
y = "cat"
print(x is y) #Outputs True
  • Also see: https://stackoverflow.com/questions/69589747/python-why-is-the-is-operator-returning-true-in-this-situation – PCM Nov 03 '21 at 03:13
  • Why do you think *it should be the same*? Which of these outcomes is unexpected? Do you understand what the `is` operator does? – juanpa.arrivillaga Nov 03 '21 at 03:18
  • In the first snippet, x and y asks for a string. In the other, it was already set to same strings. I don't quite understand how the first snippet returns false when the second returns true. – Christian Salinas Nov 03 '21 at 03:21
  • @ChristianSalinas why? Do you **understand what the `is` operator does**? Again, *what were you expecting*? – juanpa.arrivillaga Nov 03 '21 at 03:24
  • I understand that `is` checks if the objects point to the same memory location. But, I was expecting `True` to return in the first snippet. I guess I overlook the `input` as well that's why it was confusing to me. – Christian Salinas Nov 03 '21 at 03:30
  • @ChristianSalinas wait wait wait. Why did you expect *either* of these to print `True`? If anything, it should be *unexpected* that `True` ever came up. Indeed, the fact that it happens to be `True` in the second case is *not something you can depend on*, and is completely based on implementation details – juanpa.arrivillaga Nov 03 '21 at 03:32
  • 1
    Check out [this answer](https://stackoverflow.com/a/25758019/5014455) from one of the linked duplicates, I think it addresses everything in very good detail – juanpa.arrivillaga Nov 03 '21 at 03:34

2 Answers2

1

The is operator in python is used to check if two objects point to the same memory location.

In the second case, when python runs, for optimization purposes both x and y point to the same memory location. However, in the first case, x and y are not defined until the user inputs a value during run time. So, they're both allocated memory in different locations.

PCM
  • 2,881
  • 2
  • 8
  • 30
Vens8
  • 85
  • 1
  • 8
1

From this Real Python article:

The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and !=, except when you’re comparing to None.

>>> x = None
>>> y = None
>>> id(x); id(y)
4389651888
4389651888
>>> x is y
True

== calls the __eq__ method of an object, is checks whether the id() of two objects is equal (memory address).

The rest of the article I linked is really informative; it talks about how Python will give the same id to small integers by default, and that you can use the sys.intern() method to ensure string variables point to the same object in memory as well.

Sparrow1029
  • 592
  • 5
  • 13