Python: list of empty lists creates references not copy

In Python, you can create a list with an element repeated N times quite easily with the following syntax:

    >>> a = [1] * 5
    >>> print(a)
    [1,1,1,1,1]

Here we create a list with a simple element (1) not an object. As soon as you manipulate objects, you need to be cautious:

    >>> a = [[1]] * 5
    >>> print(a)
    [[1],[1],[1],[1],[1]]

so far so good but if you change an element, you change them all:

   >>> a[0].append(2)
   >>> print(a)
   [[1,2],[1,2],[1,2],[1,2],[1,2]]

The reason being that in [[1]], the first element is duplicated using a reference not a copy.
Instead, you could use:

    >>> a = [[1] for i in range(5)]
Please follow and like us:
This entry was posted in Python and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published.