0

I want to:

  1. create a copy of a global list that already exists,
  2. modify the contents of this new list without affecting the original one,
  3. print both lists

all inside a function.

My code:

original_list = ['tom', 'adam', 'john']
def a():
    new_list = original_list
    new_list[1] = 'simon'
    print(original_list, new_list)

a()

Expected result:

['tom', 'adam', 'john'] ['tom', 'simon', 'john']

Actual result:

['tom', 'simon', 'john'] ['tom', 'simon', 'john']

Please explain why my code behaves the way it does and not as I expect it to.

Thanks in advance!

Tom
  • 53
  • 1
  • 4
  • 5
    Because lists are mutable, and you're not creating a copy in your code. ``new_list = original_list`` is just telling python that both variable names should point to the same variable object in memory. To create a copy, you can use the ``copy.copy`` or ``copy.deepcopy`` from the ``copy`` module, or the list-built-in ``list.copy`` (note: this is a shallow copy, like ``copy.copy``). – Mike Scotty Jul 29 '19 at 13:13
  • 1
    https://nedbatchelder.com/text/names.html – Alex Hall Jul 29 '19 at 13:16

2 Answers2

5

This is caused because you are not copying the list but pointing to the same list with a different variable.

If you are using Python3.3+ you can use the method copy on the original array when assigning it to the new variable. If not you can try slicing it list[:].

1

If you append the original_list members , and not equalizing it to new_list , then it works

original_list = ['tom', 'adam', 'john']
new_list=[];
def a():
    [new_list.append(k) for k in original_list ]
    new_list[1] = 'simon'
    print(original_list, new_list)

a()

then output will be :

['tom', 'adam', 'john'] ['tom', 'simon', 'john']
FabioSpaghetti
  • 790
  • 1
  • 9
  • 35