Python List Methods
Table of Contents
In the last lesson, we learned about Python List Operations. Now let’s use built-in list methods to add, remove, and arrange items.
Let’s Talk About Tools for Lists
We have a list. Maybe it is a shopping list. Maybe it is a list of scores. Maybe it is a list of names.
Now we want to do something with it. Add an item. Remove an item. Find an item. Sort the list. Reverse it.
That is what list methods are for.
A method is like a function, but it belongs to a specific object. For lists, there are many built-in methods. They make working with lists much easier.
Let’s remember, lists are mutable. So most list methods change the list in place. They do not return a new list. They modify the original.
Let’s go through the most common ones.
Adding Items to a Python List
append()
Adds an item to the end of the list.
fruits = ["apple", "banana"]fruits.append("orange")print(fruits)Output
['apple', 'banana', 'orange']It changes the list in place. And it returns None. So let’s not assign the result.
fruits = fruits.append("grape") # Wrong! fruits becomes Noneextend()
Adds multiple items to the end of the list. We give it another list (or any iterable).
fruits = ["apple", "banana"]fruits.extend(["orange", "grape"])print(fruits)Output
['apple', 'banana', 'orange', 'grape']The difference between append() and extend() is important.
append()adds one item. If that item is a list, it adds the whole list as a single item.extend()adds each item from the other list one by one.
fruits = ["apple"]fruits.append(["banana", "orange"])print(fruits)Output
['apple', ['banana', 'orange']]See? The whole list became a single item. That is usually not what we want.
fruits = ["apple"]fruits.extend(["banana", "orange"])print(fruits)Output
['apple', 'banana', 'orange']That is what we want. So let’s use extend() when adding multiple items.
insert()
Inserts an item at a specific position.
fruits = ["apple", "banana", "orange"]fruits.insert(1, "grape")print(fruits)Output
['apple', 'grape', 'banana', 'orange']It inserted “grape” at index 1. The rest shifted to the right.
Removing Items from a Python List
remove()
Removes the first occurrence of a value.
fruits = ["apple", "banana", "orange", "banana"]fruits.remove("banana")print(fruits)Output
['apple', 'orange', 'banana']Only the first “banana” was removed. The second one is still there.
If the value is not found, it raises a ValueError.
fruits.remove("grape") # Error!So let’s check before removing if we are not sure.
pop()
Removes an item by index. If we do not give an index, it removes the last item.
fruits = ["apple", "banana", "orange"]fruits.pop(1)print(fruits)Output
['apple', 'orange']fruits.pop()print(fruits)Output
['apple']pop() also returns the removed item. That can be useful.
fruits = ["apple", "banana", "orange"]removed = fruits.pop()print(f"Removed: {removed}")print(f"List: {fruits}")Output
Removed: orangeList: ['apple', 'banana']clear()
Removes all items from the list. The list becomes empty.
fruits = ["apple", "banana", "orange"]fruits.clear()print(fruits)Output
[]del Keyword
We can also use the del keyword to remove an item by index or a slice.
fruits = ["apple", "banana", "orange"]del fruits[1]print(fruits)Output
['apple', 'orange']del fruits[0:2]print(fruits)Output
[]del is not a method. It is a statement. But it is useful for removing slices.
Finding Items in a Python List
index()
Returns the index of the first occurrence of a value.
fruits = ["apple", "banana", "orange"]print(fruits.index("banana"))Output
1If not found, it raises a ValueError.
count()
Counts how many times a value appears.
fruits = ["apple", "banana", "orange", "banana"]print(fruits.count("banana"))Output
2Sorting and Reversing a Python List
sort()
Sorts the list in place.
numbers = [5, 2, 9, 1, 7]numbers.sort()print(numbers)Output
[1, 2, 5, 7, 9]We can sort in reverse order.
numbers.sort(reverse=True)print(numbers)Output
[9, 7, 5, 2, 1]It also works on strings. Alphabetical order by default.
fruits = ["banana", "apple", "orange"]fruits.sort()print(fruits)Output
['apple', 'banana', 'orange']Let’s be careful. sort() changes the original list. If we do not want that, we use sorted() instead, which returns a new list.
reverse()
Reverses the list in place.
numbers = [1, 2, 3, 4, 5]numbers.reverse()print(numbers)Output
[5, 4, 3, 2, 1]Again, it changes the original. To get a reversed copy without changing the original, we use slicing [::-1].
Copying a Python List
copy()
Returns a shallow copy of the list.
original = [1, 2, 3]copied = original.copy()print(copied)Output
[1, 2, 3]Now copied is a separate list. Changing one does not affect the other.
But let’s be careful. This is a shallow copy. If the list contains nested lists, they are still shared.
Python List Methods: A Real-Life Example
Let’s build a simple to-do list manager.
todos = []
while True: print("\n1. Add task") print("2. Remove task") print("3. Show tasks") print("4. Quit") choice = input("Enter choice: ")
if choice == "1": task = input("Enter task: ") todos.append(task) elif choice == "2": task = input("Enter task to remove: ") if task in todos: todos.remove(task) else: print("Task not found") elif choice == "3": if todos: print("\nYour tasks:") for i, task in enumerate(todos, 1): print(f"{i}. {task}") else: print("No tasks yet") elif choice == "4": break else: print("Invalid choice")That uses append(), remove(), and looping. It is a simple but complete program.
Common Mistakes with Python List Methods
Mistake 1: Assigning the Result of append()
fruits = ["apple"]fruits = fruits.append("banana") # fruits becomes Noneprint(fruits)Output
NoneBecause append() returns None. It changes the list in place. So let’s not assign the result.
fruits.append("banana")print(fruits)Mistake 2: Confusing append() and extend()
fruits = ["apple"]fruits.append(["banana", "orange"])print(fruits)Output
['apple', ['banana', 'orange']]If we wanted to add the items individually, we use extend().
Mistake 3: Using remove() Without Checking
fruits = ["apple"]fruits.remove("banana") # Error!So what do we do? We check first.
if "banana" in fruits: fruits.remove("banana")Mistake 4: Forgetting That sort() Changes the Original
numbers = [3, 1, 2]numbers.sort()print(numbers)Output
[1, 2, 3]The original list is changed. If we want to keep the original, we use sorted().
Mistake 5: Using pop() on an Empty List
empty = []empty.pop() # Error!So what do we do? We check if the list is not empty first.
if empty: empty.pop()Next, we will learn about Python List Slicing and extract or change selected parts of a list.