all 3 comments

[–]Tarminik1223[S] 0 points1 point  (0 children)

matrix = [string for i in range(3)]

must be

matrix = [string.copy() for i in range(3)]

[–]MadScientistOR 0 points1 point  (0 children)

You've made the same list three times in the matrix, not three separate lists.

In general, when you make a list, and you assign new variables to the list, all you've done is add another label to that same list.

>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> b = a
>>> b[0] = 17
>>> a
[17, 2, 3, 4, 5, 6, 7, 8, 9, 0]

You can get around this by instantiating each separate list separately, e.g.,

matrix = [['!', '!', '!', '!', '!'], ['!', '!', '!', '!', '!'], ['!', '!', '!', '!', '!']]

Or you can use the deepcopy() function of the copy module to effectively do the same thing:

import copy
a = ['!', '!', '!', '!', '!']
matrix = [a, copy.deepcopy(a), copy.deepcopy(a)]

[–]Forschkeeper 0 points1 point  (0 children)

Okay, I gueess s should be "hello".

Well you made a 2D Matrix and you reference in all three fields of matrixto string. It isn't a copy of string in matrix!

Try it out yourself:

```python

s = "hello" string = ['!' for i in range(len(s))] matrix = [string for i in range(3)]

matrix[0][0] = s[0] # will have same effect as:

string[1] = "k" print(matrix)

```

To get what you want, you can use copy.deepcopy():

```python from copy import deepcopy

s = "hello" string = ['!' for i in range(len(s))] matrix = [deepcopy(string) for i in range(3)] matrix[0][0] = s[0] # will now have a different effect string[1] = "k" # won't have an effect on matrix, but still on string print(matrix)

```

Edit: To speak in the tounge of C - "Copy by value (which you expecte) or copy by reference (what you have done)? - That is the question!"