Module 5: Lists in Python
List Methods
Lists have helpful methods to add, remove, and sort items. You call them with a dot: my_list.method().
About 12 minutes
Adding items
Example code
items = ["pen"]
items.append("pencil") # add to end
print(items)
items.insert(0, "eraser") # add at index 0
print(items)Removing items
Example code
nums = [1, 2, 3, 2] nums.remove(2) # removes first 2 found print(nums) last = nums.pop() # removes and returns last print(last, nums)
Sorting
Example code
scores = [85, 92, 78] scores.sort() # sorts in place print(scores) print(len(scores)) # count items
Practice
Start with [3,1,4]. Append 1, sort, then print the list.
Key takeaways
- append() adds to the end; insert() adds at a position.
- remove() deletes a value; pop() removes the last (or at index).
- sort() orders the list in place.
Quick check: List Methods
Question 1 of 2
Which method adds one item to the end?