Python - List Methods
Overview
Estimated time: 20–30 minutes
Understand and use common list methods effectively, with notes on complexity and when to choose alternative data structures.
Learning Objectives
- Use
append
,extend
,insert
,pop
,remove
,clear
,index
,count
,sort
,reverse
. - Know performance characteristics (amortized O(1) append, O(n) insert/remove at front/middle).
- Avoid anti-patterns (e.g., repeatedly using
+=
in loops, using list for membership tests vs set).
Examples
nums = [3, 1, 4]
nums.append(1)
nums.extend([5, 9])
nums.insert(1, 2) # insert 2 at index 1
print(nums)
print(nums.count(1))
print(nums.index(4))
nums.sort()
print(nums)
Expected Output:
[3, 2, 1, 4, 1, 5, 9]
2
3
[1, 1, 2, 3, 4, 5, 9]
Guidance & Patterns
- Explain stability of Python’s Timsort (
list.sort
), and key functions viakey=
. - Contrast
append
vsextend
, andsorted(list)
vslist.sort()
. - Show why
pop(0)
is O(n) and suggestcollections.deque
for queue patterns.
Best Practices
- For frequent membership tests, prefer
set
overlist
. - For large merges, consider generators and
itertools.chain
to reduce copies.
Exercises
- Given a list of names with duplicates, deduplicate preserving order.
- Sort a list of dicts by two keys: last name, then first name.