Python list of lists

I just stumbled upon a post/problem in stackoverflow. Here I discuss it and the solution.

First check the following code segment :
>>>visited = [[False]*4]*4
>>>visited[0][1] = True
>>>print visited
>>> [[False, True, False, False], [False, True, False, False], [False, True, False, False], [False, True, False, False]]

Do you see the problem, second element of all the list changed to True! So it means [[False]*4]*4 creates a list that contains reference to the same list [False, False, False, False]

You can avoid this by following this code:
    >>> n = 4
    >>> m = 4
    >>> visited = []
    >>> for x in xrange(n):
    ...      visited.append([False] * m)
    ... 
    >>> visited
    [[False, False, False, False], [False, False, False, False], [False, False, False, False], [False, False, False, False]]
    >>> visited[0][1] = True
    >>> visited
    [[False, True, False, False], [False, False, False, False], [False, False, False, False], [False, False, False, False]]
    >>> 

Comments

Anonymous said…
With list comprehension you can do it somewhat shorter:

>>> visited = [ [ False ] *4 for i in xrange(4) ]
Dave Proffer said…
Very helpful to get peeps heads around Python's object reference model. I understand your and Toni's xrange solution, but could someone explain to a n00b like me where in the Python reference material that the two assignments below would yield the two different behaviors:

visited = [[False]*4]*4

visited = [[False, False, False, False],
[False, False, False, False],
[False, False, False, False],
[False, False, False, False]]

Thx!
Paddy3118 said…
A suggestion: Why not code in Python 3 or code in a way that works with both 2 and 3?
That use of xrange just seems ugly now and detracts from the point of repeated references..
Paddy3118 said…
There is also:

>>> y = [[]]*3
>>> y
[[], [], []]
>>> [id(item) for item in y]
[5689752, 5689752, 5689752]
>>> y[0]
[]
>>> y[0].append('Boo!')
>>> y
[['Boo!'], ['Boo!'], ['Boo!']]
>>>

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code