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}

Updated on: 19-Sep-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements