List Methods & Advanced Operations
930 words
5 min read
Visual companion
Python
Type and operator map
Python Week 1: the first filter for runtime behavior
View
Revision summary
What this note is really saying
Short form
# List Methods & Advanced Operations > **Why read this?** Beyond basic CRUD, lists have powerful built-in methods for sorting, searching, and transforming. List comprehensions — a concise way to create lists — are one of Python's most elegant features and appear heavily in exams.

List Methods & Advanced Operations
Why read this? Beyond basic CRUD, lists have powerful built-in methods for sorting, searching, and transforming. List comprehensions — a concise way to create lists — are one of Python's most elegant features and appear heavily in exams.
🎯 Learning Objectives
By the end of this topic, you will be able to:
- Use all major list methods confidently
- Create new lists using list comprehensions
- Sort lists with custom keys
- Understand shallow vs deep copying
- Use lists as stacks and queues
📋 Prerequisites
📖 Core Content
15.1 List Methods — Complete Reference
| Method | Syntax | Description | Mutates? | Returns |
|---|---|---|---|---|
| append | lst.append(x) | Add to end | Yes | None |
| extend | lst.extend(iter) | Add all items | Yes | None |
| insert | lst.insert(i, x) | Insert at index | Yes | None |
| remove | lst.remove(x) | Remove first x | Yes | None (error if not found) |
| pop | lst.pop(i) | Remove at index | Yes | The removed item |
| clear | lst.clear() | Remove all | Yes | None |
| index | lst.index(x) | Find first x | No | Index (error if not found) |
| count | lst.count(x) | Count occurrences | No | Integer |
| sort | lst.sort() | Sort in-place | Yes | None |
| reverse | lst.reverse() | Reverse in-place | Yes | None |
| copy | lst.copy() | Shallow copy | No | New list |
15.2 List Comprehensions — The Pythonic Way
What problem does this solve? Creating lists often follows a pattern: start with empty, loop, append. List comprehensions compress that into one line.
python# runnable # Traditional way squares = [] for i in range(10): squares.append(i ** 2) print("Traditional:", squares) # List comprehension squares2 = [i ** 2 for i in range(10)] print("Comprehension:", squares2) # With condition evens = [i for i in range(20) if i % 2 == 0] print("Evens:", evens) # Transform and filter names = ["alice", "bob", "charlie", "dave"] upper_long = [n.upper() for n in names if len(n) > 3] print("Upper long names:", upper_long)
Output:
pseudoTraditional: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] Comprehension: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] Evens: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] Upper long names: ['ALICE', 'CHARLIE']
Syntax:
text[expression for variable in iterable if condition]
15.3 Sorting with Custom Keys
python# runnable words = ["python", "java", "c", "javascript", "go", "rust"] # Sort by length words.sort(key=len) print("By length:", words) # Sort by last character words.sort(key=lambda w: w[-1]) print("By last char:", words) # Sort descending words.sort(key=len, reverse=True) print("By length desc:", words) # sorted() preserves original original = [3, 1, 4, 1, 5] sorted_copy = sorted(original, reverse=True) print("Original:", original) print("Sorted copy:", sorted_copy)
15.4 Shallow vs Deep Copy
python# runnable # Shallow copy — independent at top level original = [1, 2], [3, 4](/courses/may26-python/notes/1%2C%202%5D%2C%20%5B3%2C%204) shallow = original.copy() shallow[0][0] = 99 # Changes BOTH lists! print("Original:", original) print("Shallow:", shallow) # Deep copy — fully independent import copy original = [1, 2], [3, 4](/courses/may26-python/notes/1%2C%202%5D%2C%20%5B3%2C%204) deep = copy.deepcopy(original) deep[0][0] = 99 # Only changes deep print("Original:", original) print("Deep:", deep)
15.5 Worked Example 1: Flatten a 2D List
python# runnable matrix = [1, 2], [3, 4], [5, 6](/courses/may26-python/notes/1%2C%202%5D%2C%20%5B3%2C%204%5D%2C%20%5B5%2C%206) flat = [num for row in matrix for num in row] print(f"Matrix: {matrix}") print(f"Flattened: {flat}")
15.6 Worked Example 2: Filter with Comprehension
python# runnable numbers = [15, 22, 8, 31, 14, 27, 9, 3, 18, 12] # Even numbers > 10 result = [n for n in numbers if n % 2 == 0 and n > 10] print(f"Even > 10: {result}") # Numbers divisible by 3 div3 = [n for n in numbers if n % 3 == 0] print(f"Divisible by 3: {div3}")
15.7 Worked Example 3: List of Tuples Sorting
python# runnable students = [ ("Alice", 85), ("Bob", 72), ("Charlie", 90), ("Diana", 78), ("Eve", 95) ] # Sort by score descending students.sort(key=lambda s: s[1], reverse=True) print("Rankings:") for i, (name, score) in enumerate(students, 1): print(f" {i}. {name}: {score}")
15.8 Worked Example 4: Matrix Transpose
python# runnable matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] transpose = [[row[i] for row in matrix] for i in range(3)] print("Original:") for row in matrix: print(row) print("Transposed:") for row in transpose: print(row)
📐 Key Concepts Reference
| Operation | Code | Result for [3, 1, 4, 1, 5] |
|---|---|---|
| Sort | lst.sort() | [1, 1, 3, 4, 5] |
| Sort desc | lst.sort(reverse=True) | [5, 4, 3, 1, 1] |
| Filter | [x for x in lst if x > 2] | [3, 4, 5] |
| Map | [x**2 for x in lst] | [9, 1, 16, 1, 25] |
| Enumerate | list(enumerate(lst)) | [(0,3), (1,1), (2,4), (3,1), (4,5)] |
| Zip | list(zip(lst, lst2)) | Pairs elements |
⚠️ Common Pitfalls
Pitfall 1: sort() Returns None
The mistake:
new_lst = lst.sort() — now new_lst is None. Fix: lst.sort() then use lst, or new_lst = sorted(lst).Pitfall 2: Modifying List in Comprehension
The mistake: Using
lst.append(x) inside a comprehension. Fix: Comprehensions should be PURE (no side effects). Use them to create, not modify.Pitfall 3: Shallow Copy Surprises with Nested Lists
The mistake:
copy = original[:] then modifying a nested list. Fix: Use copy.deepcopy(original) for full independence.📝 Practice Questions
Q1: What does this comprehension produce?python[x * 2 for x in range(5) if x > 1]Answer:[4, 6, 8](x=2→4, x=3→6, x=4→8) Q2: Write a one-liner to get all even numbers from a list squared.Answer:python[n**2 for n in [1, 2, 3, 4, 5, 6] if n % 2 == 0] # Result: [4, 16, 36]Q3-10: Additional questions on list methods and comprehensions.(Following pattern with detailed answers.)
🔗 Cross-References
- Next Topic: Tuples
- Previous Topic: Lists Basics
- BSCS2002 PDSA: List comprehensions relate to map/filter functional programming patterns.
- Reference: Python for Everybody, Chapter 8 (Sections 8.4-8.6)
- Video: L53: Lists & sets, L57: More on lists Join Discord Previous14. Lists BasicsNext16. Tuples