0

I was trying a program in which I declared a 2D array named grid of size 5 x 5 globally in python.

grid = [[0] * 5] * 5

def main():
    global grid
    n,m = map(int,input().split())
    for i in range(n):
        li = list(map(int,input().split()))
        for j in range(m):
            if j < 5:
                grid[i][j] = li[j]
    print(grid)

if __name__ == "__main__":
    main()

Modifying the grid gives a weird answer. For example if the input is :-

2 3
1 2 3
4 5 6

2 rows and 3 columns (n and m)

It gives the following output:-

[[4, 5, 6, 0, 0], [4, 5, 6, 0, 0], [4, 5, 6, 0, 0], [4, 5, 6, 0, 0], [4, 5, 6, 0, 0]]

Even when I remove the line global grid from the main function, output remains the same. What is going on? I want it to update grid according to the input and leave the extra cells untouched i.e value 0. If input is of size 2 x 3 then only the first 2 rows and 3 columns of the grid should be modified according to the input and rest of the elements should remain 0.

1 Answers1

1

You should use:

[[0]*5 for _ in range(5)]

Instead of:

[[0] * 5] * 5

for more information, check this question.

Anwarvic
  • 12,156
  • 4
  • 49
  • 69
  • Is there any way that's faster than this? I was using the method in question for 1D lists because it was faster than list comprehension and it always worked fine. – Ashutosh Dumiyan Jun 26 '20 at 09:26
  • I think this is the fastest way... check [this thread](https://stackoverflow.com/questions/20816600/best-and-or-fastest-way-to-create-lists-in-python) – Anwarvic Jun 26 '20 at 09:37