2

I'm trying to write code that does this:

the_list = ['some list', 0, 1, 2]

def change(l):
    x = ['some other list', 3, 4, 5]
    l <- x

change(the_list)
print(the_list)    # ['some other list', 3, 4, 5]

I.e. replacing the contents of list l with the contents of x. What is the most pythonic way to do this?

Błażej Michalik
  • 4,474
  • 40
  • 55

3 Answers3

7

You can do following to replace the contents of l within the function change:

def change(l):
    x = ['some other list', 3, 4, 5]
    l[:] = x

This will replace the slice range (in this case the whole list) with contents of given iterable.

niemmi
  • 17,113
  • 7
  • 35
  • 42
  • Just be careful with aliases. If you have `list1 = ['some list']` and `list2 = list1`, running `change(list1)` will change both `list1` and `list2`. You can avoid this by instead setting `list2 = list1[:]`. – BallpointBen Mar 22 '16 at 08:55
0

The problem here is that you can't have pointers in Python. So assignment of the new object to your argument variable doesn't change the value in the outer scope. But you could do it with an object with explicit get and set methods. I borrowed the code from Simulating Pointers in Python. See also Pointers in Python? for further discussion.

class ref:
    def __init__(self, obj): self.obj = obj
    def get(self):    return self.obj
    def set(self, obj):      self.obj = obj

def change(l):
    x = ['some other list', 3, 4, 5]
    l.set(x)

the_list=ref(['some list', 0, 1, 2])
change(the_list)
print(the_list.get())    

and because you can explicitly set a list by l[:]=x, as mentioned in niemmi answer, you can do it that way too.

Community
  • 1
  • 1
Ehsan88
  • 3,569
  • 5
  • 29
  • 52
-2

The outer scope should already be accessible to the function as python will look locally then move up in the scope till it finds a variable name or errors.

So you should be able to do this.

the_list = ['some list', 0, 1, 2]

def change():
    x = ['some other list', 3, 4, 5]
    for item in x:
        the_list.append(item)

change()
print(the_list) 

Added output

['some list', 0, 1, 2, 'some other list', 3, 4, 5]
John Dowling
  • 582
  • 6
  • 23
  • I was trying to avoid appends, as these are performance monsters. Also, it was about overwriting contents of the list, not appending to it – Błażej Michalik Mar 22 '16 at 08:31
  • you can avoid the append if you wish, the point is the outer scope is available to you to do with as you wish, and you can use and it and it will change globally. – John Dowling Mar 22 '16 at 08:33
  • The outer scope is almost _never_ available. It's only available if the function is nested and called right after definition, or the list is defined globally. – Błażej Michalik Jun 01 '23 at 19:12