0

In Python, can someone explain the difference between the use of "s" and "s[:]"? Here, "s" is a sequence type?

Examples:

s = [1,2,3]
s[:] = [1,2,3]
for i in s:
  print(i)
for i in s[:]:
  print(i)

Are there any differences?

I was thinking maybe the last example means "copy of s" which would allow for modifying s inside loop? What else?

Update based on answers

Thanks everyone. This shows the difference in a very concise way.

>>> s = [1,2,3]; t = s; s[:] = [2,3,4]; print(t)
[2, 3, 4]

>>> s = [1,2,3]; t = s; s = [2,3,4]; print(t)
[1, 2, 3]
jgreen81
  • 705
  • 1
  • 6
  • 14
  • Yes `s[:]` is equivalent with `s.copy()` if s is `list`. – Boseong Choi Mar 05 '20 at 07:28
  • 2
    Try `t = s; s[:] = ...; print(t)` and compare to `s = ...`… – deceze Mar 05 '20 at 07:28
  • 1
    Slicing is used to get specific indexes, but since you are leaving both the start and end values empty, you get the entire list. This method is usually used for deep copying a list. – alec Mar 05 '20 at 07:28
  • 5
    @alec no deep copy. It is shallow copy. – Boseong Choi Mar 05 '20 at 07:29
  • It's a deep copy (assuming 1D list), a shallow copy would just be a pointer to the same list. – alec Mar 05 '20 at 07:30
  • 1
    @alec A *shallow copy* is a new list but with the same values in it. A "pointer to the same list" is… just the same list. – deceze Mar 05 '20 at 07:31
  • 1
    @alec no, that's not how those terms are used (in Python, at least). See https://docs.python.org/3/library/copy.html. – jonrsharpe Mar 05 '20 at 07:31
  • @alec see this https://docs.python.org/3.9/library/copy.html#copy.copy – Boseong Choi Mar 05 '20 at 07:32
  • It's a shallow copy, a = [set(), 1, 2, 3] id(a) 1934672263816 id(a[:]) 1934672263624 id(a[0]) 1934671565992 id(a[:][0]) 1934671565992 – Siddhant Mar 05 '20 at 07:34
  • I see. But for a 1D list there is no difference – alec Mar 05 '20 at 07:34
  • 2
    Even a 1D list can also have objects. – Siddhant Mar 05 '20 at 07:35
  • 1
    To TL;DR the duplicate: `s = [...]` assigns an entirely new list object to `s`. `s[:] = [...]` *mutates* an existing list object and overwrites all its contents. This makes a difference if other variables also point to that list object. `for i in s` iterates over the list; `for i in s[:]` iterates over a slice of the list, where the slice is the size of the entire list, in essence you iterate over a copy of the list. There's no real appreciable difference in those last two cases. – deceze Mar 05 '20 at 07:38

0 Answers0