Binding Names to Objects
Example 1: Variable Identity and Object Equality in Python
In Python, each variable to which we assign a value/container is treated as an object. When we are assigning a value to a variable, we are actually binding a name to an object.
Python3
a = "first" b = "first" # Returns the actual location # where the variable is stored print ( id (a)) # Returns the actual location # where the variable is stored print ( id (b)) # Returns true if both the variables # are stored in same location print (a is b) |
140081020184240 140081020184240 True
Example 2: List Identity and Object Equality in Python
In this example, the Python code compares the memory addresses (locations) of two list variables, a
and b
, using the id()
function. Despite having identical values, the is
keyword evaluates to False
, indicating that these lists are distinct objects in memory, highlighting the importance of memory address comparison for object identity in Python.
Python3
a = [ 10 , 20 , 30 ] b = [ 10 , 20 , 30 ] # return the location # where the variable # is stored print ( id (a)) # return the location # where the variable # is stored print ( id (b)) # returns false if the # location is not same print (a is b) |
140401704219904 140401704222464 False
Example 3: Immutable Objects and Function Parameter Behavior in Python
In this example, the Python code demonstrates the immutability of strings by passing the variable string
to the function foo()
. Despite attempting to assign a new value inside the function, the original string remains unchanged outside its scope, illustrating that string variables are immutable in Python.
Python3
def foo(a): # A new variable is assigned # for the new string a = "new value" print ( "Inside Function:" , a) # Driver's code string = "old value" foo(string) print ( "Outside Function:" , string) |
Inside Function: new value Outside Function: old value
Example 4: Mutable Objects and In-Place Modification in Python Functions
When we pass a mutable variable into the function foo and modify it to some other name the function foo still points to that object and continue to point to that object during its execution.
Python3
def foo(a): a[ 0 ] = "Nothing" # Driver' code bar = [ 'Hi' , 'how' , 'are' , 'you' , 'doing' ] foo(bar) print (bar) |
['Nothing', 'how', 'are', 'you', 'doing']
Is Python call by reference or call by value
Python utilizes a system, which is known as “Call by Object Reference” or “Call by assignment”. If you pass arguments like whole numbers, strings, or tuples to a function, the passing is like a call-by-value because you can not change the value of the immutable objects being passed to the function. Passing mutable objects can be considered as call by reference or Python pass by assignment because when their values are changed inside the function, then it will also be reflected outside the function.