-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
  • 9,280
  • 9
  • 43
  • 57
MetallicPriest
  • 29,191
  • 52
  • 200
  • 356

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
  • 2,127
  • 22
  • 36