More comprehensions
The comprehension shape works for dicts and sets too, and it can choose a value for each item instead of filtering.
words = ["tea", "milk", "tea", "jam"]
lengths = {w: len(w) for w in words}
firsts = {w[0] for w in words}
sizes = ["big" if len(w) > 3 else "small"
for w in words]
print(lengths)
print(sorted(firsts)) # ['j', 'm', 't']
print(sizes)- A trailing
iffilters: items that fail it are left out. a if condition else bbefore theforpicks a value for every item, so the result has one entry per input.- Two
forclauses run like nested loops, outer first:[(r, c) for r in range(2) for c in range(3)]. - Round brackets give a generator expression, which feeds
sum,any,all,minandmaxwithout building a list.
nums = [3, 8, 12]
print(any(n > 10 for n in nums)) # True
print(all(n > 0 for n in nums)) # TrueWhen a comprehension needs several conditions and a nested loop, a plain for loop is easier to read.
Your task
Write price_index(pairs) turning a list of (name, price) tuples into a dict from name to price, leaving out prices of 0 or less. Write labels(scores) returning a list with "pass" for each score of at least 50 and "fail" for the others.
The explanation opens here once every check passes.