The following code need slicing to replace all items in a list?

Viewed 39
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 Answers

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.

Related