menu

Python List Call by Reference

  • date_range 17/04/2017 22:08 info
    sort
    notes
    label
    python

I was writing a class in Python and there was a class variable that was supposed to be a copy of a global predefined list.

1
2
3
4
5
FOO = ['a', 'b', 'c']

class Test(object):
    def __init__(self):
        self.foo = FOO

At first everything was alright, until when there were multiple instances of the Test class. The initial value of self.foo was not constant, which came to my surprise since that variable is supposed to be initialised to FOO during creation.

Then I realised I forgot about the difference between call by reference and value. In Python, doing

1
2
foo = ['a', 'b', 'c']
bar = foo

means bar is just a pointer to foo, so any changes done to foo will be reflected in bar or vice versa. If you want foo and bar to be separate, you need to make bar a copy of foo. The simplest way is as below:

1
bar = list(foo)

However, if foo is a nested list, you will need to perform a deeper copy:

1
2
import copy
bar = copy.deepcopy(foo)

This concept applies to most mutable objects as well, such as dictionaries and user defined classes.