Back
+10 XP
Concept

Adding Items: `.append()` vs `.insert()`

Use `.append(val)` to tack an item onto the very end of a list. Use `.insert(index, val)` to wedge it in anywhere.

python
queue = ["alpha"]
queue.append("beta")      # ['alpha', 'beta']
queue.insert(0, "prime")  # ['prime', 'alpha', 'beta']
print(queue)

# 68. Adding Items: `.append()` vs `.insert()` Use `.append(val)` to tack an item onto the very end of a list. Use `.insert(index, val)` to wedge it in anywhere: ```python queue = ["alpha"] queue.append("beta") # ['alpha', 'beta'] queue.insert(0, "prime") # ['prime', 'alpha', 'beta'] print(queue) ``` Pro tip: `.append()` is fast ($O(1)$) because it just slaps the item on the back. `.insert(0, val)` forces Python to shift every single item in memory to the right ($O(n)$).

Checkpoint

Where does `.append()` place the new item?

Practice

Start with `items = [1, 2]`. Append `3` to it, then print `items`.

Terminal
01
Tap code blocks below to assemble
Available Blocks