Syncing account progress…

Back

Beginner · 10 min

Changing a list

Add, replace, and remove items in a list.

Add and replace items

append() adds one item at the end. Assign to an index to replace an existing item. These operations change the list itself.

items = ["bread", "milk"]
items.append("eggs")
items[0] = "rice"
print(items)

Output

['rice', 'milk', 'eggs']

Remove an item

remove() deletes the first matching value and raises an error if it is missing. List-changing methods like append() and remove() do not return the changed list; call them without assigning their result to the list.

items = ["bread", "milk", "bread"]
items.remove("bread")
print(items)

Output

['milk', 'bread']

Changing a list

  1. Track the list after each change.
  2. Call list-changing methods without replacing the list with their return value.

Try it yourself

Code runs on this device. When you are signed in, drafts sync to your account.

Update a shopping list

Replace the first item with rice, append eggs, and remove milk. Display the final list.

Practice