-1

I have the following code.

x = [['']*2]*2 # [['', ''], ['', '']]
x[0][0] = 'a'

This produces the following. But why? When I actually just changed the first element of the first list.

[['a', ''], ['a', '']]

Or is [['']*cols]*rows not the right way to create a matrix in Python?

petezurich
  • 7,683
  • 8
  • 34
  • 51
MetallicPriest
  • 27,365
  • 43
  • 180
  • 324

1 Answers1

1

Because python is using the same list twice and just referencing it.

You can use the function copy() for creating copies or use numpy for creating empty matrix (check https://stackoverflow.com/a/13347614/1223945)

Nader Alexan
  • 1,967
  • 20
  • 33