Possible Duplicates:
Types for which “is” keyword may be equivalent to equality operator in Python
Python “is” operator behaves unexpectedly with integers
Hi.
I have a question which perhaps might enlighten me on more than what I am asking.
Consider this:
>>> x = 'Hello'
>>> y = 'Hello'
>>> x == y
True
>>> x is y
True
I have always used the comparison operator. Also I read that is
compares the memory address and hence in this case, returns True
So my question is, is this another way to compare variables in Python? If yes, then why is this not used?
Also I noticed that in C++, if the variables have the same value, their memory addresses are different.
{ int x = 40; int y = 40; cout << &x, &y; }
0xbfe89638, 0xbfe89634
What is the reason for Python having the same memory addresses?
To find the duplicate character from the string, we count the occurrence of each character in the string. If count is greater than 1, it implies that a character has a duplicate entry in the string. In above example, the characters highlighted in green are duplicate characters.
You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.
You can't compare strings in C with ==, because the C compiler does not really have a clue about strings beyond a string-literal.
The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.
This is an implementation detail and absolutely not to be relied upon. is
compares identities, not values. Short strings are interned, so they map to the same memory address, but this doesn't mean you should compare them with is
. Stick to ==
.
There are two ways to check for equality in Python: ==
and is
. ==
will check the value, while is
will check the identity. In almost every case, if is
is true, then ==
must be true.
Sometimes, Python (specifically, CPython) will optimize values together so that they have the same identity. This is especially true for short strings. Python realizes that 'Hello' is the same as 'Hello' and since strings are immutable, they become the same through string interning / string pooling.
See a related question: Python: Why does ("hello" is "hello") evaluate as True?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With