2

I need an insight into understanding the below code. The first print gives me output: 'a' whereas on changing the value of y[0][0] to "p" it changes the value of y[0][0], y[1][0], y[2][0] and y[3][0] as well. I was expecting an output like [['p', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']] but instead got [['p', 'b', 'c'], ['p', 'b', 'c'], ['p', 'b', 'c'], ['p', 'b', 'c']]

x=["a","b","c"]
y = [x] * 4
# first print
print(y[0][0])

y[0][0] = "p"
# second print
print(y)
boom_itsme
  • 133
  • 12

1 Answers1

1

Because * operator is not exact, it's kind of funny, so use range.

It will work by replacing the below line:

y = [x] * 4

With:

y = [x.copy() for i in range(4)]

Use copy which creates a copy of something else, and actually copy is creating a same thing when printing it, but different id, different object really, so your code won't do the above reproduction again.

Also, you've got your question closed as a duplicate of:

List of lists changes reflected across sublists unexpectedly

Which have much better explanations.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114