Teaching Kids Programming – Pass by Values, References or Object-References in Python


Teaching Kids Programming: Videos on Data Structures and Algorithms

Have you wondered the parameters in Python are passed by values, or references?

For example, given the following function:

1
2
def f(x):
    x = 2
def f(x):
    x = 2

If we pass the x variable, what would the x be?

1
2
3
x = 1
f(x)
print(x) # prints 1
x = 1
f(x)
print(x) # prints 1

Pass by Values

By definition, “Pass by Values” means that the values of the variables are passed to functions as values (copies) so the modification inside the function do not affect the variables that are passed onto the function.

Pass by References

On the other hand, “Pass by References” means the variables are passed as alias to functions will be subject to changes that occur inside the functions. In other words, the changes inside the function will not be discarded.

Pass by Object References

Python uses Pass by Object-References. If the data types are immutable (can’t change) then those will be passed by values. For example: these immutable types (string, int, complex, frozenset, tuple, float, bytes) are passed by Values.

And if the data types are mutable (changable) such as list/array, set, dictionary/hash table, bytesarray, objects, then it is passed by references.

1
2
3
4
5
6
7
x = [1,2,3]
 
def f(x):
    x.append(4)
 
f(x)
print(x) # x=[1,2,3,4]
x = [1,2,3]

def f(x):
    x.append(4)

f(x)
print(x) # x=[1,2,3,4]

global keyword in Python

We can add “global” declaration inside the function to specifically reference a variable that is outside the function scope – although this may not be a good idea and generally it is a code-smell (to use global variables).

1
2
3
4
5
6
7
8
x = 1
 
def f():
  global x
  x = 2
 
f(x)
print(x) # x changed to 2
x = 1

def f():
  global x
  x = 2

f(x)
print(x) # x changed to 2

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
411 words
Last Post: Teaching Kids Programming - Left/Right Side View of a Binary Tree using Depth/Breadth First Search Algorithms
Next Post: Teaching Kids Programming - Compute the Number of Consecutive Ones Less than K using Top Down Dynamic Programming Algorithm (Recursion + Memoziation)

The Permanent URL is: Teaching Kids Programming – Pass by Values, References or Object-References in Python

Leave a Reply