1
#To store data into two dimensional array (2X2) matrix data
no_of_rows = int(input("Enter number of rows:"))
no_of_cols = int(input("Enter number of columns:"))
two_dim_array=[[0]*no_of_cols]*no_of_rows
for row in range(0,no_of_rows,1):
    for col in range(0,no_of_cols,1):
        number=int(input("Enter number to store in array:"))
        two_dim_array[row][col]=number
print(two_dim_array)

Output is:

Enter number of rows:2
Enter number of columns:2
Enter number to store in array:1
Enter number to store in array:3
Enter number to store in array:5
Enter number to store in array:7
[[5, 7], [5, 7]]

In this Python program, I'm trying to store runtime data in 2D array using index position. When I execute it, last row data is duplicated in all rows. Kindly help me on this. Thank you.

I want to know how to use 2D array in Python.

Cow
  • 2,543
  • 4
  • 13
  • 25
  • 1
    Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Swifty Jul 27 '23 at 10:37
  • Replace `[[0]*no_of_cols]*no_of_rows` with `[[0]*no_of_cols for i in range(no_of_rows)]` . The problem is that all rows are the same object as the 1st row. – Swifty Jul 27 '23 at 10:38

1 Answers1

0
two_dim_array=[[0]*no_of_cols]*no_of_rows

change definition of two_dim_array to

two_dim_array=[[0]*no_of_cols for row in range(no_of_rows)]

that way you will create a list of lists (2d array), instead of cloning last input to all the other rows