- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Pass by reference vs value in Python
All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function.
Example
#!/usr/bin/python # Function definition is here def changeme( mylist ): "This changes a passed list into this function" mylist.append([1,2,3,4]); print "Values inside the function: ", mylist return # Now you can call changeme function mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist
Output
Here, we are maintaining reference of the passed object and appending values in the same object. So, this would produce the following result −
Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
There is one more example where argument is being passed by reference and the reference is being overwritten inside the called function.
Example
#!/usr/bin/python # Function definition is here def changeme( mylist ): "This changes a passed list into this function" mylist = [1,2,3,4]; # This would assig new reference in mylist print "Values inside the function: ", mylist return # Now you can call changeme function mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist
Output
The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce the following result −
Values inside the function: [1, 2, 3, 4] Values outside the function: [10, 20, 30]
- Related Articles
- Pass by reference vs Pass by Value in java
- Describe pass by value and pass by reference in JavaScript?
- Is java pass by reference or pass by value?
- Differences between pass by value and pass by reference in C++
- What is Pass By Reference and Pass By Value in PHP?
- Is JavaScript a pass-by-reference or pass-by-value language?
- Which one is better in between pass by value or pass by reference in C++?
- How to pass arguments by reference in Python function?
- How to pass arguments by reference in a Python function?
- Pass an integer by reference in Java
- What is the difference between pass by value and reference parameters in C#?
- Value Type vs Reference Type in C#
- Value parameters vs Reference parameters vs Output Parameters in C#
- What is pass by reference in C language?
- Passing by pointer Vs Passing by Reference in C++

Advertisements