Fronto
Fronto

Reputation: 384

python objects are equal with different id's

I was trying to understand string comparison as I have gone through integer comparison or char comparison, where python compares the id of the object in memory.

what about sentence compare is it does same way if yes then below result object id are different but getting True as a result

a = "The Security Challenges Posed By 'Megxit'"
b = "The Security Challenges Posed By 'Megxit'"

print(id(a))
print(id(b))
print(a == b)
140133147022320
140133147021936
True

Upvotes: 0

Views: 1177

Answers (3)

chuck
chuck

Reputation: 1447

In python there are two types of equality - == and is.

is acts like you expected the comparison to work - it returns True if the two items have the same id. There's no difference between a is b and id(a) == id(b). Two objects have the same id only if they are actually the same object - meaning they are in the same place in memory, and the a and b are just two references to the same object.

When you create two identical strings, python might be able to understand that they are the same string, only create it once and give you two references to the same string - this is not a problem as strings are immutable. However in many cases, and in your case too, even though two objects are identical python will create two separate instances. In this case, their id won't be the same, but their content will - and this is what == is for.

== only returns True if the objects are identical in content (you can override the way it acts in your classes by implementing the __eq__ method). This is why you usually want to use ==, unless what you're is trying to find out if two variables actually point to the same thing, in which case use is, or id(a) == id(b).

Upvotes: 2

Runley
Runley

Reputation: 23

The object ID is a unique integer for that object during its lifetime. This is also the address of the object in memory. when you are comparing a and b you are comparing whether the contents of a are equal to b. which in your case returns True.

comparing object IDs will always give you a False because they are unique to each object during its lifetime.

you can compare the IDs by using 'is'

print(a is b)

or comparing the id()s

print(id(a) == id(b))

Upvotes: 2

Riccardo Bucco
Riccardo Bucco

Reputation: 15364

== is used for equality comparison (not identity comparison). To compare identities (i.e., IDs), you can use is:

a = "The Security Challenges Posed By 'Megxit'"
b = "The Security Challenges Posed By 'Megxit'"

print(a == b) # True
print(a is b) # False

Upvotes: 3

Related Questions