Quiz 2

List Methods & Advanced Operations

930 words
5 min read
Python Week 1: the first filter for runtime behavior
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:
  1. Use all major list methods confidently
  2. Create new lists using list comprehensions
  3. Sort lists with custom keys
  4. Understand shallow vs deep copying
  5. Use lists as stacks and queues

📋 Prerequisites


📖 Core Content

15.1 List Methods — Complete Reference

MethodSyntaxDescriptionMutates?Returns
appendlst.append(x)Add to endYesNone
extendlst.extend(iter)Add all itemsYesNone
insertlst.insert(i, x)Insert at indexYesNone
removelst.remove(x)Remove first xYesNone (error if not found)
poplst.pop(i)Remove at indexYesThe removed item
clearlst.clear()Remove allYesNone
indexlst.index(x)Find first xNoIndex (error if not found)
countlst.count(x)Count occurrencesNoInteger
sortlst.sort()Sort in-placeYesNone
reverselst.reverse()Reverse in-placeYesNone
copylst.copy()Shallow copyNoNew 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:
pseudo
Traditional: [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

OperationCodeResult for [3, 1, 4, 1, 5]
Sortlst.sort()[1, 1, 3, 4, 5]
Sort desclst.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]
Enumeratelist(enumerate(lst))[(0,3), (1,1), (2,4), (3,1), (4,5)]
Ziplist(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

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.