Python - Lists
Overview
Estimated time: 25–35 minutes
Work with Python lists: a mutable, ordered sequence type. Learn creation, access, slicing, copying, and common methods.
Learning Objectives
- Create and manipulate lists; understand mutability.
- Use slicing and copying patterns safely.
- Apply common methods: append,extend,insert,remove,pop,sort,reverse.
Prerequisites
Basics
nums = [1, 2, 3]
nums.append(4)
nums.extend([5, 6])
print(nums[0], nums[-1])
print(nums[1:4])
Copying (don’t alias by accident)
a = [1, 2, 3]
b = a            # alias; both refer to same list
c = a.copy()     # shallow copy
b.append(9)
print(a)  # [1, 2, 3, 9]
print(c)  # [1, 2, 3]
Sorting
items = [3, 1, 2]
items.sort()             # in-place
print(items)
print(sorted(items, reverse=True))  # new list
Common Pitfalls
- Using *to create nested lists:[[0]*3]*2duplicates references. Use a comprehension:[[0 for _ in range(3)] for _ in range(2)].
- Modifying a list while iterating over it; iterate over a copy.
Checks for Understanding
- What’s the difference between list.sort()andsorted(list)?
- How do you make a shallow copy of a list?
Show answers
- list.sort()sorts in place;- sorted()returns a new list.
- a.copy(),- list(a), or- a[:].
Exercises
- Deduplicate a list while preserving order.
- Sort a list of dicts by a key using key=withlambda.