Lists in Python are mutable, which means their elements can be:

  • updated
  • modified
  • replaced
  • reassigned

Modify a Single Item Using Index

To change one item, use the index position and assign a new value

Python
fruits = ["apple", "banana", "cherry"] fruits[1] = "orange" print(fruits) # Output: # ['apple', 'orange', 'cherry']

Here, we replaced "banana" with "orange".

Modify Multiple Items Using Slicing

You can replace a range of items using slice assignment

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

This replaces elements at indices 1, 2, 3 with new values.

Insert Items Without Removing

If the replacement list is longer than the slice, new items are inserted

Python
nums = [1, 2, 3] nums[1:1] = [9, 8] print(nums) # Output: # [1, 9, 8, 2, 3]

Here nums[1:1] is an empty slice, so the new values are inserted at index 1.

Replace Elements Using Loops

You can use a loop to update elements based on a condition

Python
values = [10, 20, 30, 40] for i in range(len(values)): values[i] += 5 print(values) # Output: # [15, 25, 35, 45]

This adds 5 to every element.

Change Elements with enumerate()

Using enumerate() lets you iterate with index and value

Python
colors = ["red", "blue", "green"] for idx, val in enumerate(colors): if val == "blue": colors[idx] = "purple" print(colors) # Output: # ['red', 'purple', 'green']

Modifying Nested List Items

If a list contains another list, you can change the inner item using multiple indices

Python
nested = [1, [2, 3, 4], 5] nested[1][1] = 99 print(nested) # Output: # [1, [2, 99, 4], 5]

Replace Items Using List Method

You can update all occurrences of a value using a list comprehension

Python
nums = [2, 2, 3, 2, 4] nums = [10 if x == 2 else x for x in nums] print(nums) # Output: # [10, 10, 3, 10, 4]

This replaces all 2s with 10s.

Important Notes

  • Lists are mutable, so they support in-place updates.

  • Indexing starts at 0; accessing outside the valid index raises an IndexError.

  • When modifying slices, Python adjusts the list length automatically.