Python – pass by reference

Python Tutorials (31 Part Series)

1 How to use ‘not equal’ operator in Python?
2 How to use exponents in Python?
27 more parts…
3 How to check if file exists in Python?
4 How to represent an infinite number in Python?
5 Various ways to sum numbers in Python
6 Python – pass by reference
7 4 Ways to implement Python Switch Case Statement
8 How to create a list of lists in Python?
9 Python regex: How to search and replace strings
10 How to copy a list in Python?
11 Python rename file: How to rename a file in Python
12 How to calculate the length of an array in Python?
13 How to use Open() in Python?
14 How to sort dictionary by value in Python?
15 How to get Timestamp in Python?
16 How to block a comment in Python?
17 How does return() in Python work?
18 Python constructors – How to use them?
19 Python append to string – How is it done?
20 Python list contains: How to check if an item exists in list?
21 Python Initialize List – How to do it?
22 How to print a list in Python?
23 Python remove file – How to delete a file?
24 What are Identifiers in Python?
25 Python Reserved Words List – Your Complete Guide
26 Different Arithmetic operators in Python
27 Different Comparison operators in Python
28 Different Assignment operators in Python
29 What are the Control Statements in Python?
30 Looping Statements in Python
31 What is a while loop in Python?

In this tutorial, we will learn how to use pass by reference in Python. Variables work differently in Python than in any other programming language known to us. It is a memory location with a unique address whereas in Python, variables are not declared beforehand but the data decides the data type.

Table of Contents

  1. What is pass by reference
  2. Pass by reference vs value in Python
  3. Python Object Model
  4. Closing Thoughts

What is pass by reference?

Before we jump into the technical details, let’s first see what does pass and by reference actually mean.

By pass we mean to provide an argument to a function. Whereas by reference means that the argument that has been passed to the function is a reference to a variable that is already existing in the memory. Now that we have cleared that, now we can learn about pass by reference.

In pass by reference, the variable is passed into the function directly while the variable acts as a Package that comes with the objects. Because you’ve given the function a reference to an existing variable, any operations you execute on it will have a direct effect on the variable it refers to.

Pass by reference vs value in Python

When you give function parameters via reference, you’re just passing references to values that already exist. When you pass arguments by value, on the other hand, the arguments become independent copies of the original values.

Pass by value

Any other operation performed will not have any effect on the original value as the argument passed to the function is copied. It only changes the value of the copy created within the function.

Input:

def function(int):
int+=100
print("Inside function call ",int)
int=100
print("Before function call ",int)
function(int)
print("After function call ",int)
def function(int):
  int+=100
  print("Inside function call ",int)

int=100
print("Before function call ",int)
function(int)
print("After function call ",int)
def function(int): int+=100 print("Inside function call ",int) int=100 print("Before function call ",int) function(int) print("After function call ",int)

Enter fullscreen mode Exit fullscreen mode

Here, a copy of the argument is created, and changes are made to that copy such that the original value is not affected. As a result, the original value is printed after the function call.

Output:

Before function call 100
Inside function call 200
After function call 100
Before function call 100                                       
Inside function call 200
After function call 100 
Before function call 100 Inside function call 200 After function call 100

Enter fullscreen mode Exit fullscreen mode

In this, we assigned the variable the value ‘100’ and changed it to ‘200’, but the change was not seen outside the function i.e. int is still ‘100’. Hence proved, it is pass by value method.

Pass by reference

This method passes a reference to the original arguments, and any operation performed on the parameter affects the actual value. It alters the value in both function and globally.

Input:

def function(int):
int.append('B')print("Inside function call",int)
int=['A']
print("Before function call",int)
function(int)
print("After function call",int)
def function(int):
    int.append('B')print("Inside function call",int)

int=['A']
print("Before function call",int)
function(int)
print("After function call",int)
def function(int): int.append('B')print("Inside function call",int) int=['A'] print("Before function call",int) function(int) print("After function call",int)

Enter fullscreen mode Exit fullscreen mode

When a list is used, its reference is supplied into the function, and any modifications to the list have an effect even after the method has been called.

Output:

Before function call ['A']
Inside function call ['A', 'B']
After function call ['A', 'B']
Before function call ['A']          
Inside function call ['A', 'B']                  
After function call ['A', 'B']
Before function call ['A'] Inside function call ['A', 'B'] After function call ['A', 'B']

Enter fullscreen mode Exit fullscreen mode

In the above example, function() returns a string and also modifies the value of int. This shows that Python supports the pass by reference method.

Python Object Model

It’s best if we first understand what Python objects are and how to characterize them. In Python, everything is an object. Object’s identity, data type and object’s content characterize every object.

# the identity of `int`
id(int)
3578332784044
# the type of `int`
type(int)
# the contents of `int`
int [1, 2, 3]
# the identity of `int`
id(int)
3578332784044       

# the type of `int`
type(int)

# the contents of `int`
int [1, 2, 3]           
# the identity of `int` id(int) 3578332784044 # the type of `int` type(int) # the contents of `int` int [1, 2, 3]

Enter fullscreen mode Exit fullscreen mode

As we can see above, id is the built-in function you use to query the identity of an object, and type is the built-in function you use to query the type of an object.

Closing Thoughts

Python operates differently than the other programming languages when it comes to the moving of the arguments. Since you’re giving the function a reference to an existing variable, all operations performed on this reference will directly affect the variable to which it refers. One can learn about other Python-related concepts here.

Python Tutorials (31 Part Series)

1 How to use ‘not equal’ operator in Python?
2 How to use exponents in Python?
27 more parts…
3 How to check if file exists in Python?
4 How to represent an infinite number in Python?
5 Various ways to sum numbers in Python
6 Python – pass by reference
7 4 Ways to implement Python Switch Case Statement
8 How to create a list of lists in Python?
9 Python regex: How to search and replace strings
10 How to copy a list in Python?
11 Python rename file: How to rename a file in Python
12 How to calculate the length of an array in Python?
13 How to use Open() in Python?
14 How to sort dictionary by value in Python?
15 How to get Timestamp in Python?
16 How to block a comment in Python?
17 How does return() in Python work?
18 Python constructors – How to use them?
19 Python append to string – How is it done?
20 Python list contains: How to check if an item exists in list?
21 Python Initialize List – How to do it?
22 How to print a list in Python?
23 Python remove file – How to delete a file?
24 What are Identifiers in Python?
25 Python Reserved Words List – Your Complete Guide
26 Different Arithmetic operators in Python
27 Different Comparison operators in Python
28 Different Assignment operators in Python
29 What are the Control Statements in Python?
30 Looping Statements in Python
31 What is a while loop in Python?

原文链接:Python – pass by reference

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享
The God only arranges a happy ending. If it is not happy, it means that it is not the final result.
上天只会安排的快乐的结局。如果不快乐,说明还不是最后结局
评论 抢沙发

请登录后发表评论

    暂无评论内容