How do you turn a list of daily prices into daily returns in one line of Python?
Coding
Easy
A Python puzzle about computing returns from a list of prices in one line.
Published
November 16, 2026
NoteQuestion
A stock’s daily closing prices are in a Python list, prices = [100, 102, 99, 105]. Write one line of Python that turns this list into the list of the stock’s daily returns, as decimals.
so each return needs a price and the price before it. The slice prices[1:] is [102, 99, 105], so zip(prices, prices[1:]) pairs each price, yesterday, with the next one, today, and the list comprehension computes today / yesterday - 1 for each pair:
\(t\)
yesterday, \(P_{t-1}\)
today, \(P_t\)
\(r_t\) by (1)
1
100
102
102/100 − 1 = 0.02
2
102
99
99/102 − 1 ≈ −0.0294
3
99
105
105/99 − 1 ≈ 0.0606
The function zip stops after three pairs, because prices[1:] is one price shorter. Python has zip built in, so the line needs no import.
Two common slips use index positions:
Line
The slip
[prices[i] / prices[i - 1] - 1 for i in range(len(prices))]
at i = 0, prices[-1] is the last price, so the list starts with a false return, 100/105 − 1 ≈ −0.0476
[prices[i + 1] / prices[i] - 1 for i in range(len(prices))]
at i = 3, prices[4] does not exist, and Python raises an IndexError
NoteCode: returns in one line
prices = [100, 102, 99, 105]returns = [today / yesterday -1for yesterday, today inzip(prices, prices[1:])]print([round(r, 4) for r in returns])