Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do I write a function with output parameters (call by reference) 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. However, Python doesn't have traditional "output parameters" like C++ or C#. Instead, we can achieve similar functionality through several approaches.
You can achieve call-by-reference behavior in the following ways ?
Return a Tuple of the Results
The most Pythonic approach is to return multiple values as a tuple ?
# Function Definition
def demo(val1, val2):
val1 = 'new value'
val2 = val2 + 1
return val1, val2
x, y = 'old value', 5
# Function call
result = demo(x, y)
print(result)
print("x remains:", x) # Original values unchanged
print("y remains:", y)
('new value', 6)
x remains: old value
y remains: 5
Passing a Mutable Object (List)
When you pass a mutable object like a list, modifications inside the function affect the original object ?
# Function Definition
def demo2(a):
# 'a' references a mutable list
a[0] = 'new-value'
# This changes a shared object
a[1] = a[1] + 1
args = ['old-value', 5]
print("Before:", args)
demo2(args)
print("After:", args)
Before: ['old-value', 5] After: ['new-value', 6]
Passing a Dictionary that Gets Mutated
Dictionaries are also mutable, so changes persist after the function call ?
def demo3(args):
# args is a mutable dictionary
args['val1'] = 'new-value'
args['val2'] = args['val2'] + 1
args = {'val1': 'old-value', 'val2': 5}
print("Before:", args)
# Function call
demo3(args)
print("After:", args)
Before: {'val1': 'old-value', 'val2': 5}
After: {'val1': 'new-value', 'val2': 6}
Using a Class Instance
You can pack values in a class instance and modify its attributes ?
class Namespace:
def __init__(self, **args):
for key, value in args.items():
setattr(self, key, value)
def func4(args):
# args is a mutable Namespace
args.val1 = 'new-value'
args.val2 = args.val2 + 1
args = Namespace(val1='old-value', val2=5)
print("Before:", vars(args))
# Function Call
func4(args)
print("After:", vars(args))
Before: {'val1': 'old-value', 'val2': 5}
After: {'val1': 'new-value', 'val2': 6}
Comparison
| Method | Pythonic? | Best For |
|---|---|---|
| Return Tuple | Yes | Most cases, functional style |
| Mutable List | Sometimes | Simple data modifications |
| Dictionary | Sometimes | Named parameters |
| Class Instance | Sometimes | Complex data structures |
Conclusion
While Python doesn't have true output parameters, you can achieve similar behavior using mutable objects or by returning multiple values. The tuple return approach is most Pythonic and preferred in most cases.
