Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python modifying list within function

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]
like image 798
Zining Zhu Avatar asked Dec 15 '22 18:12

Zining Zhu


1 Answers

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().

like image 143
venpa Avatar answered Jan 02 '23 14:01

venpa