Why did changing one list change another?

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 = watchlist
same.append("CCC")
own = ["AAA", "BBB"].copy()
own.append("DDD")
print(watchlist, same is watchlist, same == watchlist)
print(own, own is watchlist)
['AAA', 'BBB', 'CCC'] True True
['AAA', 'BBB', 'DDD'] False

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.

import copy

book = [["AAA", 10], ["BBB", 5], ["CCC", 20]]
shallow = book.copy()
deep = copy.deepcopy(book)
shallow[0][1] = 20
deep[1][1] = 99
print(book)
print(deep)
[['AAA', 20], ['BBB', 5], ['CCC', 20]]
[['AAA', 10], ['BBB', 99], ['CCC', 20]]

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.

def add_trade(trade, log=[]):
    log.append(trade)
    return log

def add_trade_safely(trade, log=None):
    log = [] if log is None else list(log)
    log.append(trade)
    return log

for trade in ["AAA 10", "BBB 5"]:
    print(add_trade(trade), add_trade_safely(trade))
['AAA 10'] ['AAA 10']
['AAA 10', 'BBB 5'] ['BBB 5']

Your turn

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.

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)
[['AAA', 40], ['BBB', 10], ['CCC', 40]] [['AAA', 20], ['BBB', 5], ['CCC', 20]]