Lists
A list is an ordered, mutable sequence. Ordered means each element has a fixed position and that position is stable until the list is modified. Mutable means the list can be changed in place, which distinguishes it from a string or a tuple. A list may contain values of different types, though in practice a list usually holds one kind of thing.
TP53 EGFR 3
Modifying a list
append adds one element to the end. extend adds every element of another
sequence. insert places an element at a given index and shifts the rest.
remove deletes the first element equal to its argument and raises
ValueError if none matches. pop removes and returns an element by index,
defaulting to the last.
['KRAS', 'TP53'] EGFR
These methods modify the list and return None. Writing genes = genes.append("MYC")
therefore replaces the list with None, which is a common and silent error.
Sorting
sort orders a list in place and returns None. sorted returns a new sorted
list and leaves its argument unchanged. Prefer sorted unless the in-place
behaviour is specifically required.
[7, 12, 30, 45] [30, 12, 45, 7] [7, 12, 30, 45]
Both accept a key function, applied to each element to produce the value used
for comparison, and a reverse flag. Sorting is stable: elements comparing
equal keep their original relative order.
[('TP53', 120), ('EGFR', 120), ('BRCA1', 12)]
References and copying
Assigning a list to a second name does not copy it. Both names refer to the same object, so a change made through one is visible through the other.
[1, 2, 3, 4] [1, 2, 3, 4] True
To obtain an independent list, use list(a), a.copy() or the full slice
a[:]. Note that these produce a shallow copy: the new list is independent,
but the elements inside it are still shared. For a list of lists, modifying an
inner list is visible through both copies.
[1, 2, 3] [1, 2, 3, 4] False
Lists compared with tuples
A tuple is an immutable sequence, written with parentheses. Use a tuple for a fixed-size collection whose positional elements carry structural meaning, such as coordinate pairs or database records; use a list for homogeneous sequences of variable length. Because tuples are immutable they can be used as dictionary keys, which lists cannot.
chr17 2
Task
Write top_n(values, n). It receives a list of integers and returns the n
largest values in descending order as a list. The input list must not be
modified, so sort a copy rather than sorting in place.
Test cases · 2
| # | via | input | expected stdout |
|---|---|---|---|
| 1 | stdin | 30 12 45 7 88 3 | [88, 45, 30] |
| 2 | stdin | 5 5 5 2 | [5, 5] |
Hints · 2
01Hint
sorted(values, reverse=True) returns a new list.
02Hint
Slice the first n items off the sorted result.