Skip to content
Advertisement

Why is python printing weird results while using the nested loop here?

I was given an array of strings and I want to split each of the individual strings into separate characters and store them in a separate 2-D array. I wrote the following code:-

# The given array
grid = ['1112', '1912', '1892', '1234']

# Creating a new 2D array
mat = [[None]*len(grid)]*len(grid)
for i in range(0,len(grid)):
    for j in range(0,len(grid)):
        mat[i][j] = grid[i][j]
print(mat)

But doing this gives weird values in my two-dimensional array, mat. Each of the row of the 2D array mat gets printed as [‘1′,’2′,’3′,’4’] but this should be the value of the last row only.

I shall be thankful if someone could answer my query.

Advertisement

Answer

mat = [[None]*len(grid)]*len(grid)

This statement is creating a relational 2D array (matrix), so whenever you are updating a line, it will update all the other lines.

You should be using this to create an empty 2D array:

mat = [[None for i in len(grid)] for j in range(len(grid))]

As @marc commented, you can also pass one list comprehension as width = height here

mat = [[None]*len(grid) for _ in range(len(grid))]
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement