How do I build a list in one line with a comprehension?
Write the loop that builds a list as one line, pair a list with its shifted copy using zip, keep only the items that pass a test, and number items with enumerate.
After this lesson, you can build a list of returns in one line and pick out the days with a fall.
How do I turn a loop into a comprehension?
[expression for item in items] builds a list with one value of expression per item, which replaces a loop that starts an empty list and appends. Pairing each close with the next one, zip(closes, closes[1:]), gives each day’s return in one line, Tuesday’s first: \(68 / 64 - 1 = 0.0625\).
The closes are a made-up stock’s closes in dollars from Monday to Friday. As in the lesson on slicing, closes[1:] starts at Tuesday, and zip pairs it with the list that starts at Monday and stops at the shorter one. for prior, today in ... puts the two closes of each pair under two names.
The following box builds the returns with a loop and with a comprehension and checks that they agree.
A comprehension suits a result that one expression gives, and a loop suits a calculation with several steps.
How do I keep the falls or label every day?
An if at the end of a comprehension keeps only the items that pass its test, and an if ... else before the for gives every item one of two values. Only Wednesday’s −0.0625 passes r < 0, and Thursday’s zero gets the label "down" from the two-way choice, because zero fails r > 0.
The following box filters the falls and labels every day.
print([r for r in returns if r <0])print(["up"if r >0else"down"for r in returns])
[-0.0625]
['up', 'down', 'down', 'up']
A second choice, "up" if r > 0 else "down" if r < 0 else "flat", gives Thursday its own label.
How do I find the days of the falls?
enumerate(returns) pairs each return with its position, counting from 0, so the comprehension can keep the positions of the falls and read their days. Wednesday is at position 1 of days.
The following box prints the days with a fall.
print([days[i] for i, r inenumerate(returns) if r <0])
['Wed']
enumerate(days, start=1) numbers the items from 1 for a reader, and the default of 0 matches list positions.
Your turn
Print the day and the return in percent, rounded to two decimals, for each day with a fall or no change. You should see [('Wed', -6.25), ('Thu', 0.0)].
TipShow answer
zip(days, returns) pairs each day with its return, and r <= 0 keeps the falls and the zero.
print([(day, round(r *100, 2)) for day, r inzip(days, returns, strict=True) if r <=0])