0

Say that we have a list my_num=[1,2,3,4,5]. Applying repr() on that list returns a representation of this object as a string, say a=repr(my_num). I thought that calling my_num.__repr__() would yield the same object.

However:

>>> my_num=[1,2,3,4,5]
>>> a=repr(my_num)
>>> a is my_num.__repr__()
False

Why is this happening?

Alonme
  • 1,364
  • 15
  • 28
user430191
  • 245
  • 1
  • 3
  • 10

3 Answers3

2

Very simply, each call returns a string image of my_num. Python will fold small integers, but not a string of any complexity. Each call returns a separate string object, so they have different id values.

is compares id's; == compares values.

>>> my_num=[1,2,3,4,5]
>>> repr(my_num)
'[1, 2, 3, 4, 5]'
>>> a = repr(my_num)
>>> id(a)
139786829689392
>>> a
'[1, 2, 3, 4, 5]'
>>> b = my_num.__repr__()
>>> b
'[1, 2, 3, 4, 5]'
>>> id(b)
139786829689264
>>> a is b
False
>>> a == b
True
Prune
  • 76,765
  • 14
  • 60
  • 81
1
>>> my_num = [1, 2, 3, 4, 5]
>>> id(repr(my_num))
140357224404912
>>> id(my_num.__repr__())
140357224404976
>>> repr(my_num) == my_num.__repr__()
True

As you can see id is different (i.e. these are different objects), but they are equal.

buran
  • 13,682
  • 10
  • 36
  • 61
0

There is a difference between equality and identity. using repr(obj) and obj.__repr__() is the same, however the repr function creates a new string object, and hence the two objects that are created are not identical.

You can even see that:

>>> my_num=[1,2,3,4,5]
>>> my_num.__repr__() is my_num.__repr__()
False

Check these for more info:

Python: Why does ("hello" is "hello") evaluate as True?

Why does comparing strings using either '==' or 'is' sometimes produce a different result?

Alonme
  • 1,364
  • 15
  • 28