Python list reversing function confusion

Viewed 81
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]
1 Answers

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.

Related