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 :
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:
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
>>> visited = [ [ False ] *4 for i in xrange(4) ]
visited = [[False]*4]*4
visited = [[False, False, False, False],
[False, False, False, False],
[False, False, False, False],
[False, False, False, False]]
Thx!
That use of xrange just seems ugly now and detracts from the point of repeated references..
>>> y = [[]]*3
>>> y
[[], [], []]
>>> [id(item) for item in y]
[5689752, 5689752, 5689752]
>>> y[0]
[]
>>> y[0].append('Boo!')
>>> y
[['Boo!'], ['Boo!'], ['Boo!']]
>>>