0

I was wondering, if someone could explain this behavior in python while initializing matrix in python in the following way

rows,cols = 3,3
visited = [[False]*rows]*cols
visited[0][0] = True 
print visited
[[True, False, False], [True, False, False], [True, False, False]]

As apposed to

visited = []
for i in range(rows):
   visited.append([False]*cols)
visited[0][0] = True
print visited
[[True, False, False], [False, False, False], [False, False, False]]

I am not sure, why in the first case all the elements of first col gets initialized to true.

1 Answer 1

2

Oswald shot the 35th president of the US, and then a certain John Fitzgerald Kennedy died. Why? Because they're the same person.

[[False]*rows]*cols will first construct an array [False, False, False] - let's call it John - then construct another array that has three Johns in it. Not three copies of John - three references to John.

A simpler demonstration of the same principle:

a = [False]
b = a
a[0] = True
b[0]
# => True

b's [False] is not just a copy of a's [True]: there is only one [True], with two names for it (a and b).

The difference can easily be seen in this visualisation (click "forward" to step through the program):

  • Three Johns

    john = [False] * 3
    three_johns = []
    for i in range(3):
        three_johns.append(john)
    three_johns[1][1] = True
    
  • Three random guys

    three_random_guys = []
    for i in range(3):
        random_guy = [False] * 3
        three_random_guys.append(random_guy)
    three_random_guys[1][1] = True
    

Thus, the easiest way to initialise a 2D matrix properly is this:

[[False] * rows for _ in range(cols)]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.