1

We know that in python you can multiply a list by a number:

[2]*3=[2,2,2]

I used this idea to create a 2d array:

exploded=[["O"]*7]*6

resulting in

[['O', 'O', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', 'O', 'O']]

However, when I try to change an element of this 2d array:

exploded[0][0]=9

instead of only that one element at position (0,0) changes, all elements at position (x,0) changes where x is 0 to len(exploded)-1.

[[9, 'O', 'O', 'O', 'O', 'O', 'O'], [9, 'O', 'O', 'O', 'O', 'O', 'O'], [9, 'O', 'O', 'O', 'O', 'O', 'O'], [9, 'O', 'O', 'O', 'O', 'O', 'O'], [9, 'O', 'O', 'O', 'O', 'O', 'O'], [9, 'O', 'O', 'O', 'O', 'O', 'O']]

If I assign the 2d array to exploded directly, then this issue doesn't occur, so I think it has to be something about multiplying lists by a number. Can someone explain what the error/bug here is and how [2]*3 actually works?

One Curious Person
  • 193
  • 1
  • 1
  • 4
  • You have multiple pointers to the same list, not different lists – mozway Dec 02 '21 at 01:33
  • It's not "multiplication" as in maths. The asterisk operator in this case is used to duplicate the same object (same memory location). – Selcuk Dec 02 '21 at 01:34

0 Answers0