Comparing strings using '==' and 'is'

Possible duplicates:
Types for which the keyword is may be equivalent to the equality operator in Python
Python "is" statement behaves unexpectedly with integers

Hey.

I have a question that may perhaps enlighten me more than I ask.

Consider this:

>>> x = 'Hello' >>> y = 'Hello' >>> x == y True >>> x is y True 

I have always used the comparison operator. I also read that is compares the memory address and therefore in this case returns True

So my question is: is this another way of comparing variables in Python? If so, why is this not used?

I also 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 that Python has the same memory addresses?

+6
python
source share
5 answers

There are two ways to check equality in Python: == and is . == will check the value, and is will check the identifier. In almost every case, if is true, then == should be true.

Sometimes Python (in particular, CPython) will optimize the values ​​together so that they have the same identifier. This is especially true for short lines. Python understands that "Hello" is the same as "Hello", and since strings are immutable, they become the same by combining strings / strings.

See a related question: Python: Why ("hello" welcomes ") is rated as True?

+9
source share

This is an implementation detail and should not be relied upon at all. is compares identifiers, not values. Short strings are interned, so they map to the same memory address, but that doesn't mean you have to compare them to is . Stick to == .

+11
source share

This is because of a Python function called String interning , which is a method of storing only one copy, each string value is different .

+8
source share

In Python, both strings and integers are immutable, so you can cache them. Integers ranging from -5 to 256 and small lines (I don’t know the exact size of atm) get cached, so they are one and the same object. x and y are just names related to these objects.

Also == compares equals values, and is compares for object identity. None True and False are global objects, for example, you can rebuild False to True .

The following shows that not everything is cached:

 x = 'Test' * 2000 y = 'Test' * 2000 >>> x == y True >>> x is y False >>> x = 10000000000000 >>> y = 10000000000000 >>> x == y True >>> x is y False 
+1
source share

In Python, variables are simply names pointing to an object (and they can point to the same object). In C ++, variables also determine the actual memory that is reserved for them; therefore they have different memory addresses.

For Python string interpolation and the differences between the two comparison operators, see carl response .

+1
source share

All Articles