Python:Fail to reverse a list in global frame with an assignment statement in a function

Question:

For example, if I write the following code:

>>> lst = [1, 2, 3]
>>> lst
[1, 2, 3]

Then I can reverse lst using the following code:

>>> lst = lst[::-1]
>>> lst
[3, 2, 1]

However, when I tried this:

>>> def rev(lst):
...     lst = lst[::-1]
...
>>> lst = [1, 2, 3]
>>> rev(lst)
>>> lst
[1, 2, 3]

The above output shows lst is not reversed successfully.
How to explain it?

Asked By: Deler

||

Answers:

def rev(lst):
    return lst[::-1]


lst = [1, 2, 3]

print(rev(lst))

You need to return the value in the function and then print the function with the list variable passed in, or you can assign the reversed list to a new variable and print that.

What you’re currently doing is calling a function that returns nothing and then calling the lst variable which is returning the assigned list.

Answered By: andrew
list1 = [1, 2, 3]

def rev(list2): # create function rev
  list = list2[::-1] # reverse the local list
  return list # you need this to return the value back, or it will go nowhere

list1 = rev(list1) # rev function will now return a value, so you save it to the list1 variable
print(list1) # [3, 2, 1]
Answered By: Toby Cm

Yes, your list is passed "by reference" so to speak. But then with the assignment you create a new object, and since you’re not returning it, it’s lost. Just check the ids of the objects to see that:

def rev(lst):
    print(id(lst))
    lst=lst[::-1]
    print(id(lst))

lst=[1,2,3]
rev1(lst)
                   
2503633156360
2503632976776
Answered By: gimix
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.