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?
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.
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]
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 id
s 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
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?
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.
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]
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 id
s 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