How to mutate a list with a function in python?

后端 未结 2 1928
醉话见心
醉话见心 2020-12-17 18:12

Here\'s a pseudocode I\'ve written describing my problem:-

func(s):
   #returns a value of s

x = a list of strings
print func(x)
print x #these two should          


        
2条回答
  •  独厮守ぢ
    2020-12-17 18:44

    func(s):
       s[:] = whatever after mutating
       return s
    
    x = a list of strings
    print func(x)
    print x
    

    You don't actually need to return anything:

    def func(s):
        s[:] = [1,2,3]
    
    x = [1,2]
    print func(x)
    print x # -> [1,2,3]
    

    It all depends on what you are actually doing, appending or any direct mutation of the list will be reflected outside the function as you are actually changing the original object/list passed in. If you were doing something that created a new object and you wanted the changes reflected in the list passed in setting s[:] =.. will change the original list.

提交回复
热议问题