🎓 A1Learner
🔍

Python Change List Items

Changing a list item replaces the item at an index with a new value. A list can change after it is made.

Replace by index

One item has a spelling mistake. Replace it by its index.

shopping = ["milk", "egs", "bread", "butter"]
shopping[1] = "eggs"
print(shopping)

Replace a slice range

Two old items are replaced by three new ones. The list grows by one item.

numbers = [1, 2, 3, 4]
numbers[1:3] = [20, 30, 40]
print(numbers)

Insert at a position

A method is a function that belongs to a value. You call it with a dot, like shopping.insert(...).

shopping = ["milk", "eggs", "bread", "butter"]
shopping.insert(2, "tea")
print(shopping)

Example

shopping = ["milk", "egs", "bred", "cheese"]
shopping[1] = "eggs"
shopping[2] = "bread"
shopping.insert(0, "coffee")
print(shopping)

Key points

  • Use my_list[index] = value to replace the item at that index
  • Replacing a slice range swaps several items at once
  • A slice replacement can grow or shrink the list
  • Use insert(index, item) to squeeze a new item in at a position
  • insert() moves the later items one place to the right

In this example, the shopping list starts with two spelling mistakes. shopping[1] = "eggs" fixes the item at index 1. shopping[2] = "bread" fixes the item at index 2. Then insert(0, "coffee") puts the forgotten coffee at the very start. The final print shows the fixed list.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does this code print? nums = [1, 2, 3] nums[0] = 9 print(nums)