0

I have a global variable in one function that is used as an argument for another. How can I use it as an argument without the second function changing it?

Example:

variable = []

def bar(x):
    x[2] = 4
    print x

def foo():
    global variable 
    variable = [1, 2, 3, 4]
    bar(variable)
    print variable

Running foo() like this would output:

[1, 2, 4, 4]
[1, 2, 4, 4]

When I want it to print:

[1, 2, 4, 4]
[1, 2, 3, 4]

So is there a way to keep the original global variable for future use while still using it in the other function?

  • possible duplicate of [How to clone or copy a list in Python?](http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list-in-python) – user3467349 Jan 16 '15 at 21:49

2 Answers2

2

If you want the contents of the list to be passed to bar, but you don't want the alterations to affect the original list, then copy the list as you pass it in. You can do that just by changing:

bar(variable)

to:

bar(variable[:])

The [] notation can be used to create slices of lists, which are copies of particular ranges of indexes.
[:] specifically gives you a copy of the whole list.

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • Idk why this was downvoted, but this is the correct answer, perhaps you should mention that variable[:] slices the list to make a copy of the full list. – user3467349 Jan 16 '15 at 21:48
  • @user3467349 I don't know either. Thanks for the suggestion. – khelwood Jan 16 '15 at 21:52
1

If you want to pass a copy of the list, just use bar(variable[:]). Like this:

variable = []

def bar(x):
    x[2] = 4
    print x

def foo():
    global variable 
    variable = [1, 2, 3, 4]
    bar(variable[:])
    print variable

This will output:

>>> foo()
[1, 2, 4, 4]
[1, 2, 3, 4]
user2435860
  • 778
  • 3
  • 9
  • 22