I am trying to let a function modify a list by passing the list's reference to it. The program below shows when I pass a list into the function, only a local variable is generated. Is there any ways to select some members from that list within a function? Thank you.
def func(list1):
list1 = list1[2:]
print(list1) # prints [2, 3]
list1 = [0, 1, 2, 3]
func(list1)
print(list1) # prints [0, 1, 2, 3]
Edit1: I also tried to use the following function. It also doesn't work. Maybe it's because in func2 list1 becomes a local variable referencing to list2.
def func2(list1):
list2 = list1[2:]
list1 = list2
print(list1) # prints [2, 3]
list1 = [0, 1, 2, 3]
func(list1)
print(list1) # prints [0, 1, 2, 3]
You have to return and assign the returned value to list1
:
def func(list1):
list1 = list1[2:]
print(list1) # prints [2, 3]
return list1
list1=func(list1)
or you have to reference list1
as global
inside func()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With