Value equality vs identity

  • Value –> equivalent contents
  • Identity –> same object

Binding Names to Objects

p = [1,2,3]
q = [1,2,3] 
p == q  # --> True    --> val is same
p is q  # --> False   --> not same obj

a = "first"
b = "first"
a is b # --> True
  • NOTE:
    • Immutable object (str, int tuple) refers to same obj if values are same
    • Mutable obj always create new object

Pass by object reference

  • Python uses neither Pass by Value nor Pass by Reference
  • But it uses Pass by Object Reference

Python code to demonstrate –> call by value

def test(string):
    string = "New value"
    print("Inside Function:", string)
string = "Old value"
test(string)
print("Outside Function:", string)

# Inside Function: New value
# Outside Function: Old value
  • Immutable objects – is used
  • So, a new object is created inside_fxn, which is different form outer the fxn

Python code to demonstrate –> call by reference

def add_more(mylist):
    mylist.append(50)
    print("Inside Function", mylist)
mylist = [10, 20, 30, 40]
add_more(mylist)
print("Outside Function:", mylist)

# Inside Function [10, 20, 30, 40, 50]
# Outside Function: [10, 20, 30, 40, 50]
  • Mutable object – is used
  • Inside_fxn new value is assigned to the same object, So, we get modified value in outside_fxn

NOTE:

  • By above example we can say python used pass by object reference
  • It depends on the object type weather values or reference be used.

Reference