Hold many values under one name, count them, pick them out by position, and add new ones.
A list holds several values in order under one name. You write it with square brackets and commas: ["AAA", "CCC"]. A watchlist is a list. So is a run of daily closing prices.
I show four things here: len() to count the items, x[0] to pick one out by position, x[-1] to pick from the end, and .append() to add one more.
Step 1. A watchlist
Three tickers, one name.
tickers = ["AAA", "CCC", "DDD"] # three values kept under one nameprint(tickers) # -> ['AAA', 'CCC', 'DDD']print(len(tickers)) # -> 3print(tickers[0]) # -> AAA <- positions start at 0print(tickers[1]) # -> CCCprint(tickers[-1]) # -> DDD <- -1 reads from the end
['AAA', 'CCC', 'DDD']
3
AAA
CCC
DDD
Python counts positions from zero. The first item sits at position 0, the second at position 1, and the third at position 2. tickers[3] stops the program with an IndexError.
Negative positions count from the end. tickers[-1] is the last item and tickers[-2] is the one before it.
.append() puts one new item on the end.
tickers.append("EEE") # puts one item on the end, in placeprint(tickers) # -> ['AAA', 'CCC', 'DDD', 'EEE']print(len(tickers)) # -> 4print(tickers[-1]) # -> EEE
['AAA', 'CCC', 'DDD', 'EEE']
4
EEE
The list changed in place. I did not write tickers = tickers.append(...), because .append() edits the list and returns nothing.
Step 2. Five closing prices
Here the order is time. Position 0 is the oldest close, and the last position is the most recent.
closes[-1] is the latest close. The same item sits at position len(closes) - 1.
print(closes[len(closes) -1]) # -> 190.5 <- the long way to reach the end
190.5
Two consecutive closes give one daily return.
latest = closes[-1] # most recent closeprior = closes[-2] # the close one day before itret = (latest - prior) / prior # one day return as a decimalprint(round(ret, 4)) # -> 0.0128
0.0128
Now a new day arrives and I append it.
closes.append(192.30) # a new day's close joins the endprint(closes) # -> [185.4, 187.2, 184.9, 188.1, 190.5, 192.3]print(len(closes)) # -> 6print(closes[-1]) # -> 192.3
The same two lines now cover the new day, because closes[-1] tracks the end of the list.
ret = (closes[-1] - closes[-2]) / closes[-2] # the two ends moved, the line did notprint(round(ret, 4)) # -> 0.0094
0.0094
Each return comes from two closes next to each other. Lesson 8 turns a whole list of closes into a list of returns.
Your turn
Make two lists that line up by position: prices = [185.40, 410.20, 128.75] and shares = [10, 4, 20]. Using indexing only, print what the last position in the book is worth.
prices[-1] and shares[-1] both point at position 2, so they describe the same holding. Nothing in Python checks the two lists stay lined up. You keep them in step yourself.