0

This is the code I'm trying to run:

def Menu():
    ##Menu actions
    old=stock_list[:]
    print(old+" before")
    Save(stock_list[:])
    print(old+" after")

def Save(list_of_stock):
    ##change each element of the list to be a code object

This is the output I get:

[["DVI cable"], [], [], []] before
[[<code object <module> at 0x037630F0, file "<string>", line 1>], [], [], []]

As you can see, even though in the 'Menu' function, old shouldn't change, but it does

HElpME
  • 45
  • 5

1 Answers1

-1

when you pass old as an argument to Save a shallow copy of old is passed into Save. When you do some changes in Save it got reflected in old as well. using deepcopy to pass that list will prevent that from happening.

from copy import deepcopy


def Menu():
    ##Menu actions
    old = stock_list[:]
    print(f"{old} before")
    Save(deepcopy(old))
    print(f"{old} after")

copy.copy(x) Return a shallow copy of x.

copy.deepcopy(x) Return a deep copy of x.

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances)

  • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

  • A deep copy constructs a new compound object and then, recursively,
    inserts copies into it of the objects found in the original.

https://docs.python.org/3/library/copy.html#module-copy

Vishal Singh
  • 6,014
  • 2
  • 17
  • 33