Lists
A list is an ordered, mutable sequence.
xs = [30, 10, 20]
xs.append(40)
print(xs[0], xs[-1]) # 30 40
print(xs[1:3]) # [10, 20]
print(xs[::-1]) # reversed copySlices never raise for out-of-range bounds. They return whatever exists, and they build a new list.
Sort in place or make a copy
xs.sort()changes the list and returnsNone.sorted(xs)returns a new list and leavesxsalone.- Both accept
reverse=Trueandkey=lenstyle functions.
Do not change a list passed to you unless that is the function's stated job. The caller may still need it.
Comprehensions
A comprehension builds a list from a loop in one expression:
nums = [1, 2, 3, 4]
big = [n * 10 for n in nums if n > 2]
print(big) # [30, 40]Your task
Write top_three(scores) returning the three largest scores, highest first, without changing the input. Write chunks(items, size) returning a list of consecutive slices of at most size items.
The explanation opens here once every check passes.