Lesson 6.2: List Methods
By the end of this lesson, you will be able to:
- Add items to lists using append(), insert(), and extend()
- Remove items using remove(), pop(), and clear()
- Sort and reverse lists using sort() and reverse()
- Search lists with count() and index()
- Understand which methods modify the list in place vs. return a new value
Adding Items to a List
my_list.method_name().
append() -- Add to the End
The append() method adds a single item to the end of a list.
fruits = ["apple", "banana"] fruits.append("cherry") print(fruits) # You can append any data type numbers = [1, 2, 3] numbers.append(4) print(numbers)
insert() -- Add at a Specific Position
The insert() method adds an item at a specific index. All items after that index shift to the right.
fruits = ["apple", "cherry", "date"] fruits.insert(1, "banana") # Insert at index 1 print(fruits) # Insert at the beginning fruits.insert(0, "avocado") print(fruits)
extend() -- Add Multiple Items
The extend() method adds all items from another list (or iterable) to the end.
fruits = ["apple", "banana"] more_fruits = ["cherry", "date", "elderberry"] fruits.extend(more_fruits) print(fruits)
append() vs extend() -- Important Difference!
# append adds the entire list as ONE item list_a = [1, 2, 3] list_a.append([4, 5]) print("append:", list_a) # extend adds each item individually list_b = [1, 2, 3] list_b.extend([4, 5]) print("extend:", list_b)
Removing Items from a List
remove() -- Remove by Value
The remove() method removes the first occurrence of a specified value.
fruits = ["apple", "banana", "cherry", "banana"] fruits.remove("banana") # Removes first "banana" print(fruits)
If the item is not found, Python raises a ValueError.
fruits = ["apple", "banana"] # fruits.remove("grape") # ValueError: list.remove(x): x not in list # Safe way: check first if "grape" in fruits: fruits.remove("grape") else: print("grape not found in list")
pop() -- Remove by Index
The pop() method removes an item at a given index and returns it. Without an argument, it removes the last item.
fruits = ["apple", "banana", "cherry", "date"] # Pop the last item last = fruits.pop() print(f"Removed: {last}") print(fruits) # Pop at a specific index second = fruits.pop(1) print(f"Removed: {second}") print(fruits)
clear() -- Remove All Items
The clear() method removes all items, leaving an empty list.
fruits = ["apple", "banana", "cherry"] fruits.clear() print(fruits)
Sorting and Reversing
sort() -- Sort In Place
The sort() method sorts the list in place (modifies the original list).
# Sort numbers in ascending order numbers = [64, 25, 12, 22, 11] numbers.sort() print(numbers) # Sort strings alphabetically names = ["Charlie", "Alice", "Bob"] names.sort() print(names) # Sort in descending order numbers = [64, 25, 12, 22, 11] numbers.sort(reverse=True) print(numbers)
sort() vs sorted()
sort() modifies the list in place and returns None. If you want a new sorted list without changing the original, use the built-in sorted() function.
original = [3, 1, 4, 1, 5] new_sorted = sorted(original) print("Original:", original) print("Sorted copy:", new_sorted)
reverse() -- Reverse In Place
The reverse() method reverses the order of elements in the list.
fruits = ["apple", "banana", "cherry"] fruits.reverse() print(fruits)
Searching Lists
count() -- Count Occurrences
The count() method returns the number of times a value appears in the list.
grades = ["A", "B", "A", "C", "A", "B"] print(f"Number of A's: {grades.count('A')}") print(f"Number of D's: {grades.count('D')}")
index() -- Find Position
The index() method returns the index of the first occurrence of a value.
fruits = ["apple", "banana", "cherry", "banana"] print(fruits.index("cherry")) print(fruits.index("banana")) # Returns first occurrence
If the value is not found, index() raises a ValueError. Always check first with in.
fruits = ["apple", "banana", "cherry"] search = "date" if search in fruits: print(f"Found at index {fruits.index(search)}") else: print(f"{search} not found")
Modifying List Elements
Since lists are mutable, you can change individual elements by assigning a new value to a specific index.
fruits = ["apple", "banana", "cherry"] print("Before:", fruits) # Change the second element fruits[1] = "blueberry" print("After:", fruits)
Practical Example: Updating Student Grades
students = ["Alice", "Bob", "Charlie"] grades = [85, 72, 90] # Bob retook the exam bob_index = students.index("Bob") grades[bob_index] = 88 print(f"Bob's updated grade: {grades[bob_index]}")
Quick Reference: All List Methods
| Method | What It Does | Returns |
|---|---|---|
append(x) | Adds x to the end | None |
insert(i, x) | Inserts x at index i | None |
extend(iterable) | Adds all items from iterable | None |
remove(x) | Removes first occurrence of x | None |
pop(i) | Removes and returns item at index i | The removed item |
clear() | Removes all items | None |
sort() | Sorts list in ascending order | None |
reverse() | Reverses the list order | None |
count(x) | Counts occurrences of x | Integer |
index(x) | Returns index of first x | Integer |
Try It Yourself
Create a list of 3 cities. Then: (1) append a new city, (2) insert a city at position 0, (3) sort the list alphabetically, (4) print the final result.
Check Your Understanding
Given: nums = [5, 3, 8, 1, 9, 3]
- What is the list after
nums.append(7)? - What does
nums.count(3)return? - What does
nums.pop()return and what is left? - What is the difference between
sort()andsorted()?
[5, 3, 8, 1, 9, 3, 7]2(the number 3 appears twice)- Returns
3(last item); list becomes[5, 3, 8, 1, 9] sort()modifies the list in place and returns None.sorted()returns a new sorted list and leaves the original unchanged.
Key Takeaways
append()adds to the end;insert()adds at a position;extend()adds multiple itemsremove()deletes by value;pop()deletes by index and returns the itemsort()andreverse()modify the list in place and returnNonecount()andindex()help you search within lists- Most list methods modify the list in place -- they do not return a new list