A list is an ordered, changeable collection of items — the most-used data structure in Python. It can hold any types (even mixed), grow and shrink, and be sorted and sliced. If you're keeping a sequence of things, it's probably a list.
Indexing & slicing
Access items by position (starting at 0), count from the end with negatives, and take sub-lists with slices:
nums = [3, 1, 4, 1, 5]nums[0] # 3 first itemnums[-1] # 5 last itemnums[1:3] # [1, 4] slice: indices 1,2 (stop exclusive)nums[:2] # [3, 1] first twonums[::-1] # [5, 1, 4, 1, 3] reversedlen(nums) # 5 length
Adding & removing
Lists are mutable — these methods change the list in place:
| Method | Does |
|---|---|
append(x) | Add x to the end |
insert(i, x) | Insert x at position i |
remove(x) | Remove the first x |
pop(i) | Remove & return item at i (last if omitted) |
sort() / reverse() | Reorder in place |
nums = [3, 1, 4]nums.append(9) # [3, 1, 4, 9]nums.insert(0, 0) # [0, 3, 1, 4, 9]nums.pop() # returns 9 → [0, 3, 1, 4]nums.sort() # [0, 1, 3, 4]nums.sort(reverse=True) # [4, 3, 1, 0]
Lists are references
a = [1, 2, 3]b = a # same list!b.append(4)print(a) # [1, 2, 3, 4] — a changed tooc = a.copy() # independent copyc.append(5)print(a) # [1, 2, 3, 4] — unchanged
Key takeaways
- 01Lists are ordered and mutable; index (0-based, negatives from the end) and slice like strings.
- 02append/insert/remove/pop modify in place; sort()/reverse() reorder in place.
- 03Lists can hold mixed types and nest arbitrarily.
- 04Assignment shares the reference — use .copy() when you need an independent list.
