Module 11: Modifying Lists

Learn how to change lists: adding, removing, and replacing elements.

🔄 Lists Can Change!

Unlike strings or numbers, lists are mutable. This means you can change their contents after they are created.

This module explores how to add items, remove items, and modify parts of a list directly. This is crucial for Data Manipulation.

Computational Thinking: Mutability

Mutability refers to an object's ability to be changed after creation. Understanding which data types (like lists) are mutable is key to predicting how your code will behave, especially when data is shared or modified in different parts of a program.

➕ Adding Elements

Two common ways: add to the end or at a specific position.

my_list = [10, 20, 30]
my_list.append(40) # Adds 40 to the end
[10, 20, 30, 40]

.append(item)

Adds a single item to the very end of the list. Simple and common.

my_list = ['a', 'b', 'd']
my_list.insert(2, 'c') # Insert 'c' at index 2
['a', 'b', 'c', 'd']

.insert(index, item)

Adds a single item at the specified index. Existing items from that index onwards are shifted to the right.

➖ Removing Elements

Several ways depending on whether you know the index or the value.

my_list = [5, 10, 15, 20]
del my_list[1] # Delete item at index 1
[5, 15, 20]

del list[index]

Removes the item at the specified index using the del keyword. Can also remove slices (more later).

my_list = ['x', 'y', 'z']
removed_item = my_list.pop(0) # Remove index 0, store it
List: ['y', 'z']
Removed: 'x'

.pop([index])

Removes the item at the specified index (defaults to the last item if no index is given) AND returns the removed item. Useful if you need the value.

my_list = [1, 2, 3, 2, 4]
my_list.remove(2) # Remove the FIRST occurrence of 2
[1, 3, 2, 4]

.remove(value)

Searches for the specified value and removes the first matching item it finds. Causes an error if the value isn't in the list.

🔪 Modifying with Slicing

Slicing isn't just for reading; you can assign to slices to replace, delete, or insert items.

letters = ['a', 'b', 'c', 'd', 'e']
# Replace index 1 and 2 ('b', 'c')
letters[1:3] = ['X', 'Y']
['a', 'X', 'Y', 'd', 'e']
# Delete index 3 and 4 ('d', 'e')
letters[3:5] = []
['a', 'X', 'Y']

Assigning to Slices

When you assign a new list (even an empty one) to a slice like my_list[start:end] = new_items, the elements within that slice range are replaced by the items in new_items.

The length of new_items doesn't have to match the length of the slice being replaced. This allows you to effectively insert or delete multiple items at once.

Assigning an empty list [] to a slice deletes the elements in that slice.

🧠 Quick Check!

Module 11 Theory Complete!

You've learned how to manipulate lists using various methods and slicing! This mutability is a powerful feature.
Ready to practice these skills? Head to the Practice Zone or tackle the Advanced Practice.