See that b = a gives a second name for the same list, make independent copies with copy and deepcopy, and keep a function from changing the list it receives.
After this lesson, you can change a trial portfolio without changing the original.
How can two names change the same list?
same = watchlist gives the list a second name and copies nothing, so appending through same changes watchlist too. is tests whether two names point to the same list, and == tests whether two lists hold the same items. .copy() makes a new list, so an append to the copy leaves the original as it was.
The following box appends through a second name and through a copy.
watchlist = ["AAA", "BBB"]same = watchlistsame.append("CCC")own = ["AAA", "BBB"].copy()own.append("DDD")print(watchlist, same is watchlist, same == watchlist)print(own, own is watchlist)
list(watchlist) and watchlist[:] also make new lists.
Why can a copy still change the original’s shares?
A portfolio stored as a list of rows has two levels, and .copy() copies only the outer list, so the copy and the original share the rows. Changing AAA’s shares through a shallow copy changes the original, while copy.deepcopy() copies the rows too.
The rows are made-up holdings, a ticker and a share count each. book[0][1] selects AAA’s row and then its share count.
The following box changes AAA’s shares through a shallow copy and BBB’s through a deep copy.
The original now holds 20 AAA shares and still 5 BBB shares.
How do I keep a function from changing a list?
Python creates a default value once, when it defines the function, so a default of [] is one list shared by every call, and each call appends to the trades of the calls before. A default of None with a new list inside the function gives each call a fresh list, and list(log) copies a list the caller passes in.
The following box calls both versions twice without a list.
Write doubled(book) that returns a new portfolio with twice the shares, and check that book keeps its counts. You should see [['AAA', 40], ['BBB', 10], ['CCC', 40]] and the original with 20, 5 and 20.
TipShow answer
The comprehension builds new rows, so the original rows stay as they are.
def doubled(book):return [[ticker, shares *2] for ticker, shares in book]print(doubled(book), book)