0

I am trying to enter elements in a 2d string matrix in python of 3 rows and 2 colums. I am trying to access the space of the first row and first column arr[0][0]. When I am inserting an element in the arr[0][0] position the same element is being inserted in arr 1[0] and arr[2][0] position. How to access one position at a time. Please help. The code snippet is given below

arr = [['']*2]*3
print(arr)
arr[0][0] = 's'
print(arr)

The output is given below:

enter image description here

EDIT : Changing the declaration from the one mentioned in the code snippet to the one given below works perfectly.

arr = [['']*2 for _ in range(3)] 

Shared it just incase somebody is facing the same problem and couldn't find the right question.

Sabster
  • 89
  • 1
  • 12
  • 1
    A better duplicate: https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly – iz_ Feb 21 '20 at 07:12
  • @iz_ Thanks a lot. Changing the declaration to "arr = [[' ']*2 for _ in range(3)]" works perfectly. – Sabster Feb 21 '20 at 07:19

0 Answers0