🔄 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.
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.
.append(item)
Adds a single item
to the very end of the list. Simple and common.
.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.
del list[index]
Removes the item at the specified index
using the del
keyword. Can also remove slices (more later).
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.
.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.
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.