0

I have this code:

def change_element(list, index, new_element):
    list[index] = new_element
    return list

example_list = [1, 2, 3]
new_list = change_element(example_list, -1, 4)
print example_list
print new_list

I don't want the variable "example_list" to be changed. I believe that the function "change_element" argument "list" is a pointer to "example_list", so when "list" is changed, "example_list" is changed. Even with this (below), "example_list" is still changed.

def change_element(list, index, new_element):
    return_list = list
    return_list[index] = new_element
    return return_list

example_list = [1, 2, 3]
new_list = change_element(example_list, -1, 4)
print example_list
print new_list

How do I prevent this from happening? I know this is possible with loops, but the lists I want to iterate are large. (maybe greater than 10,000 elements)

Andy G
  • 19,232
  • 5
  • 47
  • 69
The Turtle
  • 145
  • 1
  • 6
  • I think the question here is a lot simpler than the one it's marked as a "duplicate" of. The basic answer is that lists are mutable, and the function is just passing a reference to the list. In your second example, copying also means that you're just creating a second reference to the same list. To do what you want, you should make a copy at some point - e.g. by passing in `example_list[:]`, or using `return_list = list[:]` in your second example. – happydave Jun 22 '15 at 23:58
  • Thanks! Just wondering, does `[:]` use a loop? – The Turtle Jun 27 '15 at 15:03
  • Yes, it makes a full copy of the list, which will ultimately use a loop of some sort under the hood. – happydave Jun 28 '15 at 03:10

0 Answers0