Concept
Extending Lists: `.extend()` vs Trap
`.extend()` unrolls an iterable and adds each element individually. Using `.append()` on a list creates an awkward nested list inside it.
python
a = [1, 2]
a.extend([3, 4]) # [1, 2, 3, 4]
b = [1, 2]
b.append([3, 4]) # [1, 2, [3, 4]] - The Trap!
# 69. Extending Lists: `.extend()` vs Trap `.extend()` unrolls an iterable and adds each element individually. Using `.append()` on a list creates an awkward nested list inside it: ```python a = [1, 2] a.extend([3, 4]) # [1, 2, 3, 4] b = [1, 2] b.append([3, 4]) # [1, 2, [3, 4]] - The Trap! ``` If you want one clean list, use `.extend()`. If you accidentally use `.append()`, you just created a list trapped inside another list.
Checkpoint
What happens if you run `nums = [1]; nums.append([2, 3])`?
Practice
Combine `nums = [10, 20]` with `[30, 40]` using `.extend()`, then print `nums`.
01
Tap code blocks below to assemble
Available Blocks