
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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.
Achieve this in the following ways −
Return a Tuple of the Results
Example
In this example, we will return a tuple of the outcome −
# Function Definition def demo(val1, val2): val1 = 'new value' val2 = val2 + 1 return val1, val2 x, y = 'old value', 5 # Function call print(demo(x, y))
Output
('new value', 6)
Passing a mutable object
Example
In this example, we will pass a mutable 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] demo2(args) print(args)
Output
['new-value', 6]
Passing a Dictionary that gets mutated
Example
In this example, we will pass a dictionary −
def demo3(args): # args is a mutable dictionary args['val1'] = 'new-value' args['val2'] = args['val2'] + 1 args = {'val1': 'old-value', 'val2': 5} # Function call demo3(args) print(args)
Output
{'val1': 'new-value', 'val2': 6}
Values in Class Instance
Example
In this example, we will pack up values in class instance −
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) # Function Call func4(args) print(vars(args))
Output
{'val1': 'new-value', 'val2': 6}
- Related Articles
- Value parameters vs Reference parameters vs Output Parameters in C#
- How do we pass parameters by reference in a C# method?
- How do I call a Variable from Another Function in Python?
- Call by value and Call by reference in Java
- How to call a stored procedure that returns output parameters, using JDBC program?
- How do I call a JavaScript function on page load?
- How to pass arguments by reference in a Python function?
- Difference between Call by Value and Call by Reference
- How to pass arguments by reference in Python function?
- How do I plot a step function with Matplotlib in Python?
- How to call a function with argument list in Python?
- How do I write JSON in Python?
- How do I omit Matplotlib printed output in Python / Jupyter notebook?
- What is call by reference in C language?
- How do I use strings to call functions/methods in Python?

Advertisements