Search code examples
pythonnested-lists

Python nested lists


Why does this code:

x = [[]]*3
x[0].append('a')
x[1].append('b')
x[2].append('c')
x[0]=['d']
 
print x

print [['d'], ['a', 'b', 'c'], ['a', 'b', 'c']]?


Solution

  • This is best explained step by step:

    >>> x = [[]]*3
    >>> x
    [[], [], []]
    >>> x[0].append('a')
    >>> x
    [['a'], ['a'], ['a']]
    >>> x[1].append('b')
    >>> x
    [['a', 'b'], ['a', 'b'], ['a', 'b']]
    >>> x[2].append('c')
    >>> x
    [['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]
    >>> x[0]=['d']
    >>> x
    [['d'], ['a', 'b', 'c'], ['a', 'b', 'c']]
    

    The first statement creates a list with three references to the same element in it. So when you modify the first element, you're also modifying the second and third element. Hence, the append statements add a number to each of the elements of the list.