4
# sample 1
a = [1,2,3]
a[:] = [4,5,6]
print(a)
>>> [4,5,6]
# sample 2
a = [1,2,3]
a[:].append(4)
print(a)
>>> [1,2,3]

Why could this happen? The address of a and a[:] is different, why they are connected? What is the difference between these 2 solutions?

hcnhcn012
  • 1,415
  • 1
  • 8
  • 15
  • I'm not getting the same output as you (Python 3.6.2) - the final print returns `[4, 5, 6]` (which is expected) – TerryA Nov 11 '17 at 12:05
  • 1
    The short answer is that slice assignment is a specific operation that is semantically different from simply taking a slice, much like `+=` is semantically a different operation than `= ... + ...`. As to **why** it's designed that way: you'll probably need to ask GvR. – Daniel Pryden Nov 11 '17 at 12:05
  • @TerryA just two code samples... – hcnhcn012 Nov 11 '17 at 12:14

1 Answers1

3

a[:] hasn't the same meaning/works different ways in both examples

In the first example:

a[:] = [4,5,6]

you're assigning to a using slice assignment. It changes the contents of a. That's one way to completely change a list without changing its reference.

In the second example:

a[:].append(4)

a[:] creates a shallow copy of the list, just like list(a) or copy.copy(a), then the code appends 4 to this very copy of a, therefore, a isn't changed.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219