1

I'm fulfilling an API for a function that needs to take in a list, make a copy of it with some modifications and then set the out parameter as the copy. i.e. the function returns nothing, but must change the list object that was passed in as an argument.

Something like this:

l = [1,2,3]

def f(passed_in_list):
   different_list = [4,5,6]
   passed_in_list = different_list[:]

print(l)   # Prints [1,2,3]. How to make it [4,5,6] ?

How can I achieve this?

DBedrenko
  • 4,871
  • 4
  • 38
  • 73

3 Answers3

2

This strikes me as a dangerous design pattern, creating a function with intentional side effects on global scope. I would be careful doing things like this. That being said it doesn't look like you've called your function which may be why you aren't seeing what you expect.

Sven Harris
  • 2,884
  • 1
  • 10
  • 20
2

You need to modify the list, not the variable that points to it. And as mentioned by others, you need to call that function:

l = [1,2,3]


def f(passed_in_list):
   different_list = [4,5,6]
   passed_in_list[:] = different_list[:]


f(l)
print(l)
khachik
  • 28,112
  • 9
  • 59
  • 94
1

You need to actually call your function:

l = [1,2,3]

def f(passed_in_list):

   passed_in_list[:] = [4,5,6]

f(l)

print(l)

Yields:

[4, 5, 6]
rahlf23
  • 8,869
  • 4
  • 24
  • 54