-1

I'm a beginner in Python and I'm studying from the book Learning Python 5th edition by Mark Lutz.

In studying scoping and object reference, I've run across one thing that I quite did not understand. I understand that when you assign an object to other object, they're merely sharing a reference to the same address unless you perform top-level copying. However, I noticed that when you 'nest' the object, two objects no longer share the same address.

For example,

>>> L = [4, 5, 6]
>>> X = L * 4                   # Like [4, 5, 6] + [4, 5, 6] + ...
>>> Y = [L] * 4                 # [L] + [L] + ... = [L, L,...]

>>> X
[4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6]
>>> Y
[[4, 5, 6], [4, 5, 6], [4, 5, 6], [4, 5, 6]]


>>> L[1] = 0                    # Impacts Y but not X
>>> X
[4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6]
>>> Y
[[4, 0, 6], [4, 0, 6], [4, 0, 6], [4, 0, 6]]

This is the part I don't understand. Why does changing L object impact Y but not X?

HardStats
  • 5
  • 1

1 Answers1

3

You have 2 differents case:

  1. X = L * 4 create a new list with 4 copies of the elements of L.

  2. Y = [L] * 4 create a new list with 4 references to L. So you end up with something like: Y = [L, L, L, L]

TwistedSim
  • 1,960
  • 9
  • 23