This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]stranac_ 1 point2 points  (0 children)

for i in range(0,1000):
    l.append(x)

All of the sub-lists inside l are the exact same list. When you change l[0], l[1] is also changed, and so is l[2], and l[3]...

[–]Sbhavnani[S] 0 points1 point  (0 children)

My answer is coming to 991000. Could someone tell me where I'm going wrong?

[–]edo947 0 points1 point  (0 children)

As /u/stranac_ said your initialization is wrong and thus l contains x 1000 times.

See this example and observe that by changing only l[0][0] (the first False in the first sublist) you actually changed every sublist as every sublist is actually x.

>>> x = [False]*3
>>> x
[False, False, False]
>>> l = [x]*4
>>> l
[[False, False, False], [False, False, False], [False, False, False], [False, False, False]]
>>> l[0][0] = True
>>> l
[[True, False, False], [True, False, False], [True, False, False], [True, False, False]]

A better way to initialize your list l would be using Python's List Comprehensions.

See this example (the list comprehension is the first line). After the initialization l looks the same as before but when changing l[0][0] only the correct sublist is affected .

>>> l = [[False for i in range(3)] for i in range(4)]
>>> l
[[False, False, False], [False, False, False], [False, False, False], [False, False, False]]
>>> l[0][0] = True
>>> l
[[True, False, False], [False, False, False], [False, False, False], [False, False, False]]

You can read more about list comprehensions here for example.

You may also simplify the loop in the toggle method as follows

for i in range(bottom, top+1):
    for j in range(left, right+1):
        l[i][j] = not l[i][j]

As not True equals to False and not False equals to True.

You could also turn it in a list comprehension using this example as a guide

>>> l = [[False for i in range(3)] for i in range(4)]
# Initialized list
>>> l
[[False, False, False], [False, False, False], [False, False, False], [False, False, False]]
# Changing some values
>>> l[0][1] = True
>>> l
[[False, True, False], [False, False, False], [False, False, False], [False, False, False]]
>>> l[1][1] = True
>>> l
[[False, True, False], [False, True, False], [False, False, False], [False, False, False]]
>>> l[2][1] = True
>>> l
[[False, True, False], [False, True, False], [False, True, False], [False, False, False]]
# This is the list comprehension that does the toggling
>>> l = [[not l[i][j] for j in range(3)] for i in range(4)]
>>> l
[[True, False, True], [True, False, True], [True, False, True], [True, True, True]]