4. Lists
4.3 Change and add items
Highlights & notes
Select lesson text to highlight it, or tap Add note.
Bookmarks
Bookmark a lesson to see it here.
Lists can change after you create them.
- Change an item: assign to its index,
files[0] = "orders_v2.csv". - append(x) adds one item at the end.
- insert(i, x) adds an item at position
i. - extend(other) adds every item from another list.
Example
Python
files = ["orders.csv", "users.csv"]
files[0] = "orders_v2.csv"
files.append("events.csv")
files.insert(0, "header.csv")
files.extend(["a.csv", "b.csv"])
print(files)Output
['header.csv', 'orders_v2.csv', 'users.csv', 'events.csv', 'a.csv', 'b.csv']
Must Know:
append and extend change the list and return None. Write files.append(x) on its own line, never files = files.append(x).
Practice in Python ✓ Solved
Change the first item of cart to "pencil", append "book", then insert "bag" at the start. Print cart.
Expected output
['bag', 'pencil', 'eraser', 'book']
Reference solution
cart = ["pen", "eraser"]
cart[0] = "pencil"
cart.append("book")
cart.insert(0, "bag")
print(cart)
Question 1 · Easy
x = [1, 2]; x.append(3). What is x?
Question 2 · Medium
x = [1, 2]; x.append([3, 4]). What is len(x)?
Question 3 · Hard
x = ["b", "c"]; x.insert(0, "a"). What is x?
Key takeaways
Assign to an index to change an item. append adds one item, insert adds at a position, extend adds many.
Save your progress
Start free and your progress, code and notes stay saved. Free for 1 month, no card needed.
Start free Log in