Pass by reference in Python

There is no pass by reference in Python, so it isn’t possible to pass an variable to a function and have it assigned a new value within the function, including passing in an immutable primitive type value and having it replaced with a modified value.

It is possible to do something similar though by passing in the value inside a data structure or other object.

For example, in the following program a string has its value modified in two different ways. Firstly, a class object is used to store the string’s value, and secondly, a list is used for the same purpose.

class Wrapper(object):
    def __init__(self, value):
        self.value = value

def pass_by_reference1(wrapper):
    wrapper.value = wrapper.value + ", and spam"

def pass_by_reference2(wrapper):
    wrapper[0] = wrapper[0] + ", and spam"

def main():
    var1 = Wrapper("A string");
    pass_by_reference1(var1)
    print var1.value

    var2 = ["Another string"]
    pass_by_reference2(var2)
    print var2[0]

if __name__ == '__main__':
    main()