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 appendvsextend, andsorted(list)vslist.sort().
- Show why pop(0)is O(n) and suggestcollections.dequefor queue patterns.
Best Practices
- For frequent membership tests, prefer setoverlist.
- For large merges, consider generators and itertools.chainto 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.