2
def square_please(some_list):
some_list[:] = [x**2 for x in some_list]

Hello, why do we need the [:] in our code in order for it to replace every item in the list with its squared value? It is not intuitive to me why we need the slicing at all.

I would think because we are assigning a new list to some_list, it would overwrite the previous list, similar to if we had the following:

list1 = [3,4,5]
list1 = [6,7,8]
  • 1
    It will work even if you remove ':' It is basically used to splice the array by specifying the indexes before and after the ':' – Sudhanshu Bhagwat May 20 '20 at 05:17
  • 1
    Why do you even want to slice the list. Just assign it as you normally do. – Underoos May 20 '20 at 05:19
  • 2
    They do two *completely* different things. `a = [3, 4, 5]` assigns *a new list* to the name `a`. The old list that was being referred to by `a` is *not affected directly*. If it *happens* to no longer be referenced, it is garbage collected. `a[:] = [3, 4, 5]` **mutates** the list object being referenced by `a`, and this change will be visible to all other references to that same object (obviously, because it is the same object) – juanpa.arrivillaga May 20 '20 at 05:20
  • 2
    So, consider, `a = [1, 2]; b = a` then compare what happens if you do `a = [3, 4]; print(b)` versus `a[:] = [3, 4]; print(b)` – juanpa.arrivillaga May 20 '20 at 05:21

1 Answers1

2

If you do not use [:] it will create an entirely new list and assign it to some_list and any previous references to some_list will not be modified. In some cases this is not an issue. If you return some_list it would return a new list and both the squared and unsquared one could be used, but other times you want to change the value in-place and this is how you would do that. See this question.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
RedKnite
  • 1,525
  • 13
  • 26