0

Are booleans made pointers? I had this weird case:

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]]

How do I avoid this?

Thanks!

yifanwu
  • 1,595
  • 3
  • 14
  • 25
  • 1
    This has been asked many, many times before. In fact, it is probably among the most frequently asked Python questions here. – NPE Aug 09 '14 at 17:04

1 Answers1

0

It appears that when you do [[False]*4]*4, you're creating a list of [False,False,False,False], and then making four references to that exact same list instead of four copies. You may have to use a for loop or a list comprehension to avoid this happening.

visited = []
for i in range(4):
  falselist = [False]*4
  visited.append(falselist)
TheSoundDefense
  • 6,753
  • 1
  • 30
  • 42