A Wandering Mind · Computer Science
PYTHON GUIDE

Learn · Run · Break · Fix

A learning series from A Wandering Mind

Eighteen interlinked lessons on strings, lists, files, exceptions, and dictionaries—with original explanations, runnable examples, real output, and supporting CPSC 1301K lectures.

course.py
>>> guide = {
...   "lessons": 18,
...   "modules": 5,
...   "python": "3.10+"
... }
>>> guide["goal"] = "understand it"
Module 2 · Lists · Lesson 5 of 18

Changing and Removing List Items in Python

Python lists are mutable, which means the contents of an existing list can change after the list is created. You can replace a value at a known index, delete an item by position, remove the first matching value, or pop an item out and keep the removed value for later use. This lesson focuses on how those operations differ and what happens to the remaining list after each change.

Prerequisite: Complete Indexing Lists and Measuring Length first. You should already understand positive and negative indexes before changing or deleting by position.

Lists can change after they are created

In Lesson 3, you created lists and saw them as ordered containers. In Lesson 4, you used indexes to read particular positions. The next step is realizing that those positions are not permanently tied to their original values. A list is mutable: Python allows the same list object to be changed in place.

That makes lists fundamentally different from strings. A string such as "cat" cannot have its first character replaced in place. With a list, however, assigning a new value to an existing index is normal. The list remains a list; one of its elements simply changes.

Example 1 · Replace one item by indexVerified
colors = ["red", "green", "blue"]
colors[1] = "teal"
print(colors)
['red', 'teal', 'blue']

The assignment target is colors[1], so Python replaces the item currently stored at index 1. The list still contains three elements. Nothing is inserted and nothing shifts position because replacement changes the value occupying an existing slot.

Replacement is not insertion. Writing items[2] = value changes an already existing position. It does not create a new position beyond the end of the list. If the index does not exist, Python raises an IndexError.

Negative indexes work for assignment too

The indexing rules from the previous lesson still apply when the index appears on the left side of an assignment. If -1 means the final item when reading a list, it also means the final item when replacing one. This is useful when the list may change length but the meaning of “the last item” stays the same.

Example 2 · Replace the final itemVerified
temperatures = [68, 71, 75, 79]
temperatures[-1] = 80
print(temperatures)
[68, 71, 75, 80]

The operation changes only the final value. The earlier indexes remain valid and the length stays four. This distinction matters because deletion behaves differently: when an item disappears, every item after it moves one position toward the beginning.

Delete by position with del

Python’s del statement removes an item when you know the index you want to eliminate. Unlike assignment, deletion changes the length of the list. The elements to the right of the deleted position shift left to close the gap.

Example 3 · Delete a known positionVerified
tasks = ["email", "meeting", "backup", "lunch"]
del tasks[2]
print(tasks)
['email', 'meeting', 'lunch']

Before the deletion, "lunch" was at index 3. After "backup" is deleted, "lunch" moves to index 2. That shifting behavior is important whenever your program stores or calculates indexes and then mutates the same list afterward. An index that referred to one value before deletion may refer to a different value after the list changes.

Remove by value with remove()

Sometimes you do not care where an item is located. You know the value itself and want the first matching occurrence removed. That is the job of list.remove(value). It searches from the beginning of the list and deletes the first element equal to the requested value.

The phrase first matching occurrence matters when duplicates exist. If the same value appears twice, one call to remove() removes only the earliest match. The later duplicate remains.

Use pop() when you need the removed value

pop() is another removal operation, but it gives the removed item back to your program. With no argument, it removes and returns the final element. With an integer index, it removes and returns the item at that position. That makes it useful when deletion is also part of a larger operation—for example, taking the next item from a stack-like list and then processing that item.

Example 4 · Compare remove() and pop()Verified
cities = ["Atlanta", "Macon", "Savannah", "Macon"]
cities.remove("Macon")
removed = cities.pop()
print(cities)
print(f"Removed last: {removed}")
['Atlanta', 'Savannah']
Removed last: Macon

The first call removes the earliest "Macon", leaving the later one untouched. Then pop() removes that remaining final item and returns it, which is why the program can store it in removed. This example also reconnects the list operation to formatted strings: a removed value can immediately become part of a message or another calculation.

Replaceitems[index] = value

Changes an existing slot. Length stays the same.

Delete by positiondel items[index]

Removes a known index. Later items shift left.

Delete by valueitems.remove(value)

Removes the first matching value.

Remove and returnitems.pop()

Removes an item and returns it to the program.

Choosing between del, remove(), and pop()

The three removal forms overlap, but each expresses a different intention. Use del when the position is what matters and you do not need the removed value. Use remove() when you know a value but not necessarily its index. Use pop() when you want removal and the removed item itself.

That distinction makes code easier to read. A future reader can often understand why a line exists simply from the operation chosen. Python has many additional list methods, and Lesson 9 will examine them as a larger toolbox. Here, remove() and pop() are included because they are fundamental ways to make an item disappear.

Common mistakes when modifying lists

Mutation errors usually come from asking Python to change a position or value that is not actually available. The tracebacks below come from executed examples so you can see the real exceptions these mistakes produce.

Mistake 1 · Trying to assign just beyond the end
items = ["a", "b", "c"]
items[3] = "d"
Traceback (most recent call last):
  File "/tmp/awm_lesson5/mistake1_assignment_out_of_range.py", line 2, in <module>
    items[3] = "d"
    ~~~~~^^^
IndexError: list assignment index out of range

A three-item list has indexes 0, 1, and 2. Assignment can replace one of those positions, but it cannot create index 3. To add new elements, use an operation designed to grow a list rather than pretending an out-of-range position already exists.

Mistake 2 · Deleting an index that does not exist
items = ["a", "b", "c"]
del items[5]
Traceback (most recent call last):
  File "/tmp/awm_lesson5/mistake2_del_out_of_range.py", line 2, in <module>
    del items[5]
        ~~~~~^^^
IndexError: list assignment index out of range

del still depends on a valid index. If the position cannot be read because it lies outside the list, it cannot be deleted either. Check the list’s length or the logic that produced the index when this error appears.

Mistake 3 · Removing a value that is absent
items = ["a", "b", "c"]
items.remove("d")
Traceback (most recent call last):
  File "/tmp/awm_lesson5/mistake3_remove_missing.py", line 2, in <module>
    items.remove("d")
    ~~~~~~~~~~~~^^^^^
ValueError: list.remove(x): x not in list

remove() does not silently ignore a missing value. If no matching element exists, Python raises ValueError. Later in the module, membership testing will give you a direct way to ask whether a value is present before attempting to remove it.

Mistake 4 · Giving pop() a string index
items = ["a", "b", "c"]
items.pop("1")
Traceback (most recent call last):
  File "/tmp/awm_lesson5/mistake4_pop_wrong_type.py", line 2, in <module>
    items.pop("1")
    ~~~~~~~~~^^^^^
TypeError: 'str' object cannot be interpreted as an integer

The optional argument to pop() is a list index, so it must behave like an integer. The string "1" looks similar when printed, but it is text rather than the integer 1. This is the same type distinction you encountered when learning to index lists.

Supporting classroom explanations

This lesson is original A Wandering Mind instructional material. The two supporting CPSC 1301K videos below reinforce the two central ideas: lists can be changed in place, and list elements can be deleted.

List Mutability — by Hyrum Carroll · 1:44. Watch on YouTube ↗ · CPSC 1301K playlist ↗

What it adds: a compact classroom explanation of why list elements can be replaced after the list has already been created.

List Deletion — by Hyrum Carroll · 1:40. Watch on YouTube ↗ · CPSC 1301K playlist ↗

What it adds: a short visual reinforcement of deleting list elements and the way the remaining positions adjust afterward.

Try it yourself

Predict each final list before opening the answer. Pay particular attention to whether the operation replaces an item, shortens the list, or returns something your program can save.

Exercise 1 · Replace the middle value

Start with tools = ["pen", "paper", "stapler"]. Replace "paper" with "notebook" using index assignment, then print the list.

Show one answer
tools = ["pen", "paper", "stapler"]
tools[1] = "notebook"
print(tools)
['pen', 'notebook', 'stapler']

Exercise 2 · Delete a stop by position

Start with stops = ["North", "Central", "South", "Airport"]. Delete "Central" using del, then print the result.

Show one answer
stops = ["North", "Central", "South", "Airport"]
del stops[1]
print(stops)
['North', 'South', 'Airport']

Exercise 3 · Remove one duplicate, then pop

Start with votes = ["yes", "no", "yes", "maybe"]. Remove only the first "yes", pop the final item into a variable, then print both the remaining list and the popped value.

Show one answer
votes = ["yes", "no", "yes", "maybe"]
votes.remove("yes")
last = votes.pop()
print(votes)
print(f"Popped: {last}")
['no', 'yes']
Popped: maybe

What you should carry into Lesson 6

You now know why Python lists are called mutable. Index assignment replaces an existing element without changing the length. del removes a known position, remove() removes the first matching value, and pop() removes an item while returning it to the program. Deletion changes the list’s length and may change the indexes of everything that follows the removed item.

Next, instead of shrinking a list or replacing its contents, you will learn how entire lists can work together. Continue to Combining and Repeating Lists to explore concatenation and the repetition operator.