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

JavaScript

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

JavaScript

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:

JavaScript

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

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement