Lists: Ordered and Changeable
Unit ID: M03-U01 Estimated active time: 25-35 minutes
Create and inspect a list
module_titles = ["Values", "Collections", "Control flow"]
print(module_titles)
print(len(module_titles))
The list contains three items in a defined order. Like strings, list indexes start at zero.
print(module_titles[0])
print(module_titles[-1])
print(module_titles[0:2])
The slice creates a new list containing the first two items.
Lists are mutable
Mutable means the collection can be changed after creation.
module_titles[0] = "Python values"
print(module_titles)
The first item changes in the same list.
Add items
module_titles.append("Functions")
module_titles.insert(3, "Debugging")
append() adds one item at the end. insert() adds an item at a chosen position and shifts later items.
To add several items from another collection:
module_titles.extend(["Files", "NumPy"])
Remove items deliberately
module_titles.remove("Debugging")
removed_title = module_titles.pop()
print(removed_title)
remove() finds a matching value and removes the first match. pop() removes and returns an item; without an index, it uses the last item.
If the value is absent, remove() raises ValueError. If the index is invalid, indexing or pop() raises IndexError.
Mixed types are possible, but meaning matters
Python allows:
mixed = ["Module 1", 8, True, None]
This may be suitable for a small row-like record, but a dictionary is often clearer when the positions have different meanings. Do not choose a list merely because Python permits it.
Practice
Start with:
topics = ["values", "strings", "lists"]
- Add
"dictionaries"at the end. - Insert
"types"after"values". - Replace
"strings"with"text". - Remove
"lists"and store the removed value. - Print the final list, its length, and the removed value.
Predict the final order before running.
Takeaway
Lists preserve order and support change. Indexing, slicing, and methods make those changes explicit. Next, we will use tuples when a grouped sequence should be treated as fixed.
