11

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 give the SAME output

When I print the value of x in the end, I want it to be the one returned by func(x). Can I do something like this only by editing the function (and without setting x = func(x))

NightShadeQueen
  • 3,284
  • 3
  • 24
  • 37
Ritvik Sharma
  • 113
  • 1
  • 1
  • 4

2 Answers2

16
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.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
13

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'] 
bakkal
  • 54,350
  • 12
  • 131
  • 107
  • 2
    Remember to not assign to `x` in the function body. Otherwise `x` will become a local variable (an object in function's namespace) and will "cover" the argument passed to function. – werkritter Jul 11 '15 at 17:24