Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there strange behavior between the IDs of equivalent strings?

From my understanding, if a variable of an immutable type is assigned a value equal to another variable of the same immutable type, they should both be referencing the same object. I am using Python 2.7.6, don't know if this is a bug.

This behaves like I how understood:

x = 'ab'
y = 'ab'
id(x) == id(y)
True

However, by altering a character, this does not behave:

x = 'a#'
y = 'a#'
id(x) == id(y)
False

Strangely though, parallel assignment is very different!

x, y = 'a#','a#'
id(x) == id(y)
True

I do not understand this behavior.

like image 657
ewong718 Avatar asked Jul 23 '15 18:07

ewong718


People also ask

How would you confirm that 2 strings have the same identity Python?

It means, if two variables are assigned the same string value, they are really referring to the same string object in memory. This fact can be verified by checking their id() value. Hence, comparison operator == for checking equality returns True if two string operands have same id() value, and False otherwise.

How do you compare two strings equal in Python?

Python strings equality can be checked using == operator or __eq__() function. Python strings are case sensitive, so these equality check methods are also case sensitive.

How do you check if a variable is equal to a string in Python?

In python programming we can check whether strings are equal or not using the “==” or by using the “. __eq__” function.


1 Answers

What you're talking about is known as string interning. This is an internal mechanism and there is no guarantee that two distinct strings would be stored in the same place in memory. This is not a bug so don't rely on such behavior. This is in the same general category as undefined behavior in C/C++.

You may be interested in this answer.

While I am able to replicate this behavior in the REPL, the comparison always returns true for me if I put the code in a file and then run it with the interpreter.

By the way there is a way to guarantee that the objects are the same though:

>>> x = intern('a#')
>>> y = intern('a#')
>>> x is y
True

More details on the subject can be found in this blog post.

like image 198
Anonymous Avatar answered Sep 28 '22 23:09

Anonymous