2
def f(x):
    x = x[::-1]
list = [1,2,3]
f(list)
print(list)

OUTPUT: [1,2,3]

Can someone explain why the list didn't reverse? In the next example it reverses, but why? I can't really understand this behavior.

def f(x):
    x[:] = x[::-1]
list = [1,2,3]
f(list)
print(list)

OUTPUT: [3,2,1]
user737163
  • 431
  • 3
  • 9
  • 7
    Because `x = x[::-1]` doesn't mutate the list in-place. It creates a *new list* and assigns it to the local variable `x`. That list is discarded when the function terminates. On the other hand, `x[:] = whatever` *does* mutate the list. Indeed, `x[:] = x[::-1]` actually creates a new list, and that new list is used to mutate the original list. You should probably read https://nedbatchelder.com/text/names.html – juanpa.arrivillaga Dec 11 '20 at 06:00
  • 3
    In any case, you should simply use the built-in method `.reverse()` to reverse a list in-place – juanpa.arrivillaga Dec 11 '20 at 06:00
  • 1
    Very good explanatoin @juanpa.arrivillaga! – Cainã Max Couto-Silva Dec 11 '20 at 06:06
  • Im confused because x[:] creates a new list, but how is that new list used to mutate the original one? @juanpa.arrivillaga – user737163 Dec 11 '20 at 06:17
  • @user737163 because `x[:] = whavtever` mutates a list, it is slice-assignment. It is essentially a call to `x.__setitem__(slice(None), whatever)` – juanpa.arrivillaga Dec 11 '20 at 06:31
  • @user737163 see this question: https://stackoverflow.com/questions/10623302/how-assignment-works-with-python-list-slice basically, the expression `x[:]` is a distinct thing from the statement `x[:] = y`. The former is equivalent to `x.__getitem__(slice(None))` and the latter is equivalent to `x.__setitem__(slice(None), y)`. – juanpa.arrivillaga Dec 11 '20 at 06:34

1 Answers1

4

As the juanpa.arrivillaga's comment,

Because x = x[::-1] doesn't mutate the list in-place. It creates a new list and assigns it to the local variable x. That list is discarded when the function terminates. On the other hand, x[:] = whatever does mutate the list. Indeed, x[:] = x[::-1] actually creates a new list, and that new list is used to mutate the original list

And you could use the built-n method .reverse() to reverse a list

mylist = [1,2,3]
mylist.reverse()
print(mylist)

Or you could use reversed:

mylist = [1,2,3]
mylist = reversed(mylist)
print(list(mylist))

And try to avoid using built-in function name list in variable names.

ppwater
  • 2,315
  • 4
  • 15
  • 29