Is there a way in Python to return a value via an output parameter?

There is no reason to, since Python can return multiple values via a tuple:

def func():
    return 1,2,3

a,b,c = func()

But you can also pass a mutable parameter, and return values via mutation of the object as well:

def func(a):
    a.append(1)
    a.append(2)
    a.append(3)

L=[]
func(L)
print(L)   # [1,2,3]

You mean like passing by reference?

For Python object the default is to pass by reference. However, I don't think you can change the reference in Python (otherwise it won't affect the original object).

For example:

def addToList(theList):   # yes, the caller's list can be appended
    theList.append(3)
    theList.append(4)

def addToNewList(theList):   # no, the caller's list cannot be reassigned
    theList = list()
    theList.append(5)
    theList.append(6)

myList = list()
myList.append(1)
myList.append(2)
addToList(myList)
print(myList)   # [1, 2, 3, 4]
addToNewList(myList)
print(myList)   # [1, 2, 3, 4]

Pass a list or something like that and put the return value in there.

Tags:

Python