How to mutate a list with a function in python?

后端 未结 2 1930
醉话见心
醉话见心 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:41

    That's already how it behaves, the function can mutate the list

    >>> l = ['a', 'b', 'c'] # your list of strings
    >>> def add_something(x): x.append('d')
    ...
    >>> add_something(l)
    >>> l
    ['a', 'b', 'c', 'd']
    

    Note however that you cannot mutate the original list in this manner

    def modify(x):
        x = ['something']
    

    (The above will assign x but not the original list l)

    If you want to place a new list in your list, you'll need something like:

    def modify(x):
        x[:] = ['something'] 
    

提交回复
热议问题