-1

Please take a look at the following code:

import numpy as np
list1 = [1,2,3]
list2 = list1
list2.append(4)
print list2
print list1

The result is [1,2,3,4] for both prints. I expected to have [1,2,3,4] for list2 and [1,2,3] for list1 since I only appended '4' to list2. It looks like the assignment list2 = list1 transferred the instruction on list2 to list1.

First, I'd like to understand why that is and second, is there a way to make a variable B that is identical to variable A but such that any instruction on B (a re-assignment for example), will modify B but not A?

Obviously, I could do

list1 = [1,2,3]
list2 = [1,2,3]
list2.append(4)

and get what I want. But what if list1 is say, a (numpy) 100x100 array? Then I'd rather have a way to 'copy' list1 to another variable than manually rewriting it.

I am not an experienced programmer and am fairly new to Python. I've also tried to formulate this question as simply as I could and have not found anything that directly answered it on this site. Please redirect me to anything I might have missed and accept my apologies in advance. Thanks!

orion2112
  • 103
  • 1
  • Note that you present plain Python lists, but talk of numpy. Different beasts: https://stackoverflow.com/questions/3059395/numpy-array-assignment-problem – Ilja Everilä Jun 25 '17 at 22:17
  • 1
    You've answered your own question. In Python, assignment *never copies*. If you want a copy, you need to *explicitely make a copy*. `numpy` arrays provide a `.copy` method that you can use. You should probably check out Ned Batchelder's [Facts and Myths about Python names and values](https://nedbatchelder.com/text/names.html). – juanpa.arrivillaga Jun 25 '17 at 22:21
  • Thanks, very useful information! – orion2112 Jun 25 '17 at 22:24
  • Also, Python variables are just names you give to objects. Objects can have multiple names, and names can be reassigned to different objects. They are not like C variables, which refer to a *location in memory*. If you dig deep into it, Python names (in Cpython anyway) are essentially C variables holding py_Object pointers. But it is best to not even worry about that and just understand the abstraction in Python (unless you come from a heavy C background). – juanpa.arrivillaga Jun 25 '17 at 22:24

1 Answers1

0

This will work.

list1 = [1,2,3]
list2 = list1[:]

Now, list2.append(4) ---> will not affect list1.

Your first attempt is only copying the references so that list1 and list2 will refer to the same variable.