In the previous chapter, you learned how to create a list, access its items with indexes and slices, and loop over it. But real programs rarely leave a list untouched. You add new items, remove old ones, search for values, and sort everything into order.
Python gives every list a set of built-in methods for exactly these jobs. In this chapter, we'll go through each one, see what it returns, how fast it is, and the mistakes beginners usually make with it.
What is a List Method?
A list method is a function that belongs to a list. You call it using a dot:
list_name.method().
Most list methods change the list in place. That means they modify the original list instead of creating a new one. Keep this in mind, because it explains most of the common mistakes we'll see later.
fruits = ["apple", "banana"]
fruits.append("mango") # changes fruits itself
print(fruits)Output:
['apple', 'banana', 'mango']Adding Items
append() – Add One Item at the End
marks = [85, 90]
marks.append(78)
marks.append(92)
print(marks)Output:
[85, 90, 78, 92]append() always adds exactly one item, and always at the end. It is the most used list method and it is very fast.
insert() – Add an Item at a Position
insert(index, item) puts the item before the given index. Everything after it shifts one place to the right.
letters = ["a", "c", "d"]
letters.insert(1, "b") # put "b" at index 1
letters.insert(0, "z") # put "z" at the very start
print(letters)Output:
['z', 'a', 'b', 'c', 'd']Here's what happens in memory when we insert "b" at index 1:
Before: [ "a" | "c" | "d" ]
↓ ↓ shift right
After: [ "a" | "b" | "c" | "d" ]If the index is bigger than the list length, Python simply adds the item at the end. No error is raised.
extend() – Add Many Items
extend() takes any iterable (a list, tuple, string, range...) and adds each of its items one by one.
nums = [1, 2]
nums.extend([3, 4])
nums.extend(range(5, 7))
print(nums)Output:
[1, 2, 3, 4, 5, 6]append() vs extend()
This is a classic interview question. Look at the difference carefully:
a = [1, 2]
b = [1, 2]
a.append([3, 4])
b.extend([3, 4])
print(a)
print(b)
print(len(a), len(b))Output:
[1, 2, [3, 4]]
[1, 2, 3, 4]
3 4append() added the whole list as one item (a list inside a list). extend() added its items separately.
Also watch out when extending with a string, because a string is iterable character by character:
words = ["hi"]
words.extend("ok")
print(words)Output:
['hi', 'o', 'k']Tip: The
+operator also joins lists, but it creates a new list:c = a + b.extend()modifies the existing list instead.
Removing Items
remove() – Remove by Value
remove(x) deletes the first occurrence of the value x.
colors = ["red", "blue", "green", "blue"]
colors.remove("blue")
print(colors)Output:
['red', 'green', 'blue']Only the first "blue" was removed. If the value does not exist, Python raises an error:
colors = ["red", "green"]
colors.remove("yellow")Output:
ValueError: list.remove(x): x not in listTo stay safe, check with in first:
colors = ["red", "green"]
if "yellow" in colors:
colors.remove("yellow")
print(colors)Output:
['red', 'green']pop() – Remove by Index and Get the Item Back
pop() removes an item and returns it, so you can use the removed value. Without an argument, it removes the last item.
stack = [10, 20, 30, 40]
last = stack.pop() # removes 40
first = stack.pop(0) # removes 10
print(last, first)
print(stack)Output:
40 10
[20, 30]Calling pop() on an empty list raises IndexError: pop from empty list, and an invalid index raises IndexError: pop index out of range.
clear() – Remove Everything
cart = ["pen", "book", "bag"]
cart.clear()
print(cart)Output:
[]The del Statement
del is not a method, but it is often used with lists. It deletes by index or by slice and returns nothing.
nums = [0, 1, 2, 3, 4, 5]
del nums[0] # delete one item
del nums[1:3] # delete a slice
print(nums)Output:
[1, 4, 5]Way to Remove | Removes By | Returns | Error If Missing |
|---|---|---|---|
| Value (first match) |
|
|
| Index (default: last) | The removed item |
|
| Index or slice | Nothing (statement) |
|
| Everything |
| No error |
Searching and Counting
index() – Find the Position of a Value
names = ["Asha", "Ravi", "Neha", "Ravi"]
print(names.index("Ravi")) # first match
print(names.index("Ravi", 2)) # start searching from index 2Output:
1
3Unlike the string method find(), which returns -1, list index() raises ValueError if the value isn't found. Use in first if you aren't sure.
count() – Count Occurrences
votes = ["yes", "no", "yes", "yes", "no"]
print(votes.count("yes"))
print(votes.count("maybe"))Output:
3
0count() never raises an error. It just returns 0 if the value isn't there.
Sorting and Reversing
sort() – Sort the List in Place
scores = [42, 7, 19, 88, 3]
scores.sort()
print(scores)
scores.sort(reverse=True)
print(scores)Output:
[3, 7, 19, 42, 88]
[88, 42, 19, 7, 3]Strings are sorted alphabetically, but note that uppercase letters come before lowercase letters, because sorting compares Unicode values:
words = ["banana", "Cherry", "apple"]
words.sort()
print(words)
words.sort(key=str.lower) # ignore case while comparing
print(words)Output:
['Cherry', 'apple', 'banana']
['apple', 'banana', 'Cherry']Sorting with a key
The key parameter takes a function. Python calls it on each item and sorts by the result. You can pass a built-in function like len, or a lambda (which you met in the Lambda Functions chapter):
words = ["kiwi", "fig", "banana", "apple"]
words.sort(key=len)
print(words)
students = [("Ravi", 72), ("Asha", 91), ("Neha", 85)]
students.sort(key=lambda s: s[1], reverse=True)
print(students)Output:
['fig', 'kiwi', 'apple', 'banana']
[('Asha', 91), ('Neha', 85), ('Ravi', 72)]The words are now ordered by length: "fig" (3), "kiwi" (4), "apple" (5), "banana" (6). When two items have the same key, Python keeps them in their original order. This is called a stable sort.
sort() vs sorted()
sorted() is a built-in function, not a method. It returns a new sorted list and leaves the original unchanged. It also works on any iterable (tuples, strings, ranges...).
original = [3, 1, 2]
new_list = sorted(original)
print(original)
print(new_list)
print(sorted("python"))Output:
[3, 1, 2]
[1, 2, 3]
['h', 'n', 'o', 'p', 't', 'y']
|
| |
|---|---|---|
Type | List method | Built-in function |
Changes original? | Yes | No |
Returns |
| A new list |
Works on | Lists only | Any iterable |
reverse() – Reverse in Place
nums = [1, 2, 3, 4]
nums.reverse()
print(nums)Output:
[4, 3, 2, 1]reverse() just flips the order. It does not sort. If you want a reversed copy instead, use slicing: nums[::-1].
Copying a List
Assigning a list to another variable does not copy it. Both names point to the same list:
a = [1, 2, 3]
b = a # same list, two names
c = a.copy() # a real copy
a.append(4)
print(b)
print(c)Output:
[1, 2, 3, 4]
[1, 2, 3]a ──┐
├──► [1, 2, 3, 4]
b ──┘
c ─────► [1, 2, 3]copy() makes a shallow copy. The outer list is new, but any lists inside it are still shared:
grid = [[1, 2], [3, 4]]
copy_grid = grid.copy()
copy_grid[0].append(99)
print(grid)Output:
[[1, 2, 99], [3, 4]]For nested lists, use copy.deepcopy() from the copy module (you'll learn about importing modules in a later chapter). lst[:] and list(lst) also make shallow copies, just like copy().
Useful Built-in Functions for Lists
These are functions, not methods, but you'll use them with lists all the time:
marks = [72, 91, 85, 60]
print(len(marks))
print(min(marks), max(marks))
print(sum(marks))
print(sum(marks) / len(marks))Output:
4
60 91
308
77.0Time Complexity of List Methods
A Python list is stored as a dynamic array: items sit next to each other in memory. That's why working at the end is fast, while working at the start or middle forces Python to shift the other items.
Operation | Time | Why |
|---|---|---|
| O(1) amortized | Adds at the end; occasionally the array grows |
| O(1) | Removes from the end |
| O(n) | Items after |
| O(n) | Items after |
| O(n) | Search, then shift |
| O(n) | Checks items one by one |
| O(k) | k = number of items added |
| O(n log n) | Uses the Timsort algorithm |
| O(n) | Touches every item |
| O(1) | Direct access |
So if you need to add or remove items at the front often, a list is the wrong tool. Python's collections.deque does that in O(1).
Common Mistakes
1. Saving the Result of sort()
Methods that change the list in place return None:
nums = [3, 1, 2]
nums = nums.sort() # wrong!
print(nums)Output:
NoneThe list was sorted, but then we replaced it with None. Write nums.sort() on its own line, or use nums = sorted(nums). The same goes for append(), extend(), insert(), remove(), reverse() and clear().
2. Removing Items While Looping
nums = [1, 2, 2, 3]
for n in nums:
if n == 2:
nums.remove(n)
print(nums)Output:
[1, 2, 3]One 2 survived! When the first 2 was removed, the second 2 shifted into its place, and the loop moved on to the next index, skipping it. The safe way is to loop over a copy or build a new list:
nums = [1, 2, 2, 3]
for n in nums[:]: # loop over a copy
if n == 2:
nums.remove(n)
print(nums)Output:
[1, 3]3. Sorting Mixed Types
items = [3, "two", 1]
items.sort()Output:
TypeError: '<' not supported between instances of 'str' and 'int'Python can't decide whether "two" is smaller than 3, so all items must be comparable with each other.
A Practical Example
Let's manage a simple to-do list using several methods together:
todo = ["Study DSA", "Buy groceries"]
todo.append("Call mom")
todo.insert(0, "Morning walk")
print("Tasks:", todo)
done = todo.pop(1) # finished "Study DSA"
print("Completed:", done)
todo.remove("Buy groceries")
todo.extend(["Revise Python", "Apply for internships"])
todo.sort()
for number, task in enumerate(todo, start=1):
print(number, task)Output:
Tasks: ['Morning walk', 'Study DSA', 'Buy groceries', 'Call mom']
Completed: Study DSA
1 Apply for internships
2 Call mom
3 Morning walk
4 Revise PythonAll List Methods at a Glance
Method | What It Does | Returns |
|---|---|---|
| Adds |
|
| Inserts |
|
| Adds every item of the iterable |
|
| Removes the first |
|
| Removes item at | The removed item |
| Removes all items |
|
| Position of the first | An integer |
| How many times | An integer |
| Sorts in place ( |
|
| Reverses in place |
|
| Shallow copy | A new list |
Final Takeaway
Python lists have just 11 methods, and you'll use append(), pop(), sort() and remove() almost every day. The key ideas to remember are:
Most list methods change the list in place and return
None.Working at the end of a list is fast (O(1)); working at the front or middle is O(n).
append()adds one item,extend()adds many.sort()changes the list,sorted()gives you a new one.
Practice: Take a list of numbers from the user, remove all duplicates without using a set, sort it in descending order, and print the second largest value.