Python Forum

Full Version: Shared reference and equality
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everybody,
I am starting to learn Python in these days: I came across the topic of shared references and equality, and I thought I had understood its basics. However, I came across an example where things were not so clear to me.
Here it is:

a = 'a'
b = 'b'
ab = 'ab'
a is 'a'     # returns True
b is 'b'     # returns True
ab is 'ab'   # returns False
Why does the 3rd statement return false? Is it linked to the lenght of the string 'ab'? Thanks for helping
Printing the id will show if you are referencing the same block of memory (is)
print(id("ab"))
## 139660486771968

x="a"
x += "b"
print(x)
## "ab"
print(id(x))
## 139660486772024  different memory location 
Small integers - -5 to 255, ASCII letters, Booleans and None have dedicated constant objects associated with them. Still, the only case when is operator is recommended is a test for None value
Like @volcano63 said, is tests if two variables point to the same object.

To check if values are the same use ==. In the example below mylist1 and mylist2 point to the same object. mylist3 is a copy of mylist1.
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 'a'
>>> b = 'b'
>>> ab = 'ab'
>>> a == 'a'
True
>>> b == 'b'
True
>>> ab == 'ab'
True

>>> mylist1 = [1, 2, 3]
>>> mylist2 = mylist1
>>> mylist1 == mylist2
True
>>> mylist1 is mylist2
True

>>> mylist3 = list(mylist1)
>>> mylist3 == mylist1
True
>>> mylist3 is mylist1
False
For other methods to create a copy see https://stackoverflow.com/questions/2612...opy-a-list
Other methods include:
import copy
 
b = a[:]
b = list(a)
b = copy.copy(a)
b = copy.deepcopy(a)   
Lewis