Python Tutorial
Python List Methods
Python has a set of built-in methods you can use on lists.
Method Cheatsheet
append, clear, copy, count, extend, index, insert, pop, remove, reverse, sort.
nums = [3, 1, 3, 2]
print(nums.count(3))
print(nums.index(1))
nums.reverse()
print(nums)index() raises ValueError
If the value is missing, catch it or check with in first.
nums = [1, 2, 3]
print(2 in nums)
print(nums.index(2))📘 Real-World Deep Dive
<code>list</code> ships with a small, predictable API: <code>append/extend/insert/pop/remove/sort/reverse/copy/clear/count/index</code>. Knowing them by heart removes entire categories of hand-rolled bugs.
Real-Life Scenario
A top-K leaderboard maintained as an unsorted history, periodically re-sorted for display.
Real-Life Example
from dataclasses import dataclass
@dataclass
class Score:
user: str
pts: int
history: list[Score] = []
events = [
("ada", 10), ("bob", 17), ("ada", 6), ("cy", 30),
("bob", -3), ("ada", 12), ("de", 22), ("cy", -5),
]
for user, delta in events:
found = next((s for s in history if s.user == user), None)
if found:
found.pts += delta
else:
history.append(Score(user, delta))
def top_k(scores: list[Score], k: int = 3) -> list[Score]:
return sorted(scores, key=lambda s: -s.pts)[:k]
print("history:", history)
print("top-3 :", top_k(history))Expected Output
history: [Score(user='ada', pts=28), Score(user='bob', pts=14), Score(user='cy', pts=25), Score(user='de', pts=22)]
top-3 : [Score(user='ada', pts=28), Score(user='cy', pts=25), Score(user='de', pts=22)]Common mistakes
list.sort()returnsNone— always call it as a statement, never assign its result.list.remove(value)raisesValueErrorif absent; use a guard or atry/except.lst += otheris in-place;lst = lst + otherrebinds — semantics differ when other lists share references.
🚀 Performance & Best Practices
- Frequent lookups? Convert:
by_user = {s.user: s for s in history}. lst.sort(key=...)caches the key per element;sorted(xs, key=fn)does not.lst.reverse()is in-place and O(n);lst[::-1]makes a new list.
🧪 Try It Yourself
- Add a method
promote(user, pts=10)that pushes a user into history or updates their score. - Build a
ranked()method that returns a sorted list but keeps the originalhistoryunchanged. - Time
sort(key=lambda s: -s.pts)vs.sort(key=attrgetter("pts"), reverse=True).