This may be difficult to explain. I want to specify two indexes, and then run a for loop. If the current x being checked in the loop is the exact same item specified at the location of the two indexes, then it should return a message.
array = [ [1,1,1,1], [2,2,2,2], [3,3,3,3], [4,4,4,4] ]
Again, here’s my array. I want it to go through the for loop and print the message out when x is the 1 at memory of array[0][0], aka the same piece of memory.
for x in array:
if x == array[0][0]:
print "%s is the object you're looking for." % x
Now, why I need it to make sure it is the same exact object in memory is because, this would loop through the following three 1’s in the first list, and return the message too, as they have the same value as the first 1. I do not need this. I need only to match actual points in memory, not values.
I think what you’re asking is how to test object identity rather than object equality.
In Python you can do this with the
isoperator, i.e.Rather than:
However, you’re going have problems with ints and strings because the Python runtime automatically re-uses objects it creates for these from a pool:
I think short strings are automatically “interned” in this way and you can force longer strings to be using the
intern()function:However, it seems the
longtype isn’t interned so you use that:However, object identity for built-in types is down to the implementation of Python rather than being in the language, and is not something you should rely on either way. I think you would be better off creating your own class of objects and writing an appropriate
__eq__method for them, i.e. write your code it works based on object equality rather than identity.