Python lists come with eleven built-in methods. Some add items, some remove them, and some search or reorder the list. This lesson is a quick reference with a working example for each method, plus the traps that catch beginners: methods that return None, case-sensitive sorting and shallow copies.
In this lesson you will learn
- Every list method and what it returns
- How to sort by your own rule with
key - The difference between
sort()andsorted() - Shallow copies vs deep copies
- How to use a list as a stack
All List Methods at a Glance
| Method | Changes the list? | Returns |
|---|---|---|
append(x) | Yes: adds x at the end | None |
extend(iterable) | Yes: adds every item | None |
insert(i, x) | Yes: puts x at index i | None |
remove(x) | Yes: deletes the first x | None (error if missing) |
pop(i=-1) | Yes: deletes the item at i | The removed item |
clear() | Yes: empties the list | None |
index(x) | No | Position of the first x |
count(x) | No | How many times x appears |
sort(key, reverse) | Yes: sorts in place | None |
reverse() | Yes: reverses in place | None |
copy() | No | A new (shallow) list |
Adding, Finding and Removing
scores = [72, 95, 68, 95, 81]
scores.append(77)
scores.extend([60, 88])
scores.insert(0, 99)
print(scores)
print(scores.index(95), scores.count(95))
removed = scores.pop(2)
scores.remove(95)
print(removed, scores)
Output
[99, 72, 95, 68, 95, 81, 77, 60, 88]
2 2
95 [99, 72, 68, 81, 77, 60, 88]
index(95) returns the first position (2) even though 95 appears twice. pop(2) removed and returned that 95, then remove(95) removed the other one.
Sorting With a key
names = ["tania", "Arif", "mitu", "Imran", "bilal"]
names.sort()
print(names)
names.sort(key=str.lower)
print(names)
print(sorted(names, key=len, reverse=True))
nums = [3, 1, 2]
print(nums.sort(), nums)
Output
['Arif', 'Imran', 'bilal', 'mitu', 'tania']
['Arif', 'bilal', 'Imran', 'mitu', 'tania']
['bilal', 'Imran', 'tania', 'Arif', 'mitu']
None [1, 2, 3]
- A plain
sort()puts capital letters before small ones, so"Imran"comes before"bilal". key=str.lowersorts by the lowercase version of each name without changing the names themselves.sorted()returns a new list and accepts the samekeyandreverseoptions; here it sorts by length, longest first.- The last line shows the classic trap:
nums.sort()returnsNone.
Copies and Using a List as a Stack
a = [[1, 2], [3, 4]]
shallow = a.copy()
shallow[0].append(99)
print(a)
import copy
deep = copy.deepcopy(a)
deep[1].append(7)
print(a, deep)
stack = []
stack.append("page1"); stack.append("page2")
print(stack.pop(), stack)
Output
[[1, 2, 99], [3, 4]]
[[1, 2, 99], [3, 4]] [[1, 2, 99], [3, 4, 7]]
page2 ['page1']
copy() makes a new outer list, but the inner lists are still shared, so append(99) through the copy also changed a. copy.deepcopy() copies every level. Finally, append() and pop() together turn a list into a stack: the last item added is the first removed, like a browser’s back button. The same idea in C is covered in Stack Data Structure in C.
Common List Method Mistakes
x = x.append(5). This setsxtoNone. Callx.append(5)on its own line.append()instead ofextend().a.append([1, 2])adds one nested list.- Using a list as a queue.
pop(0)shifts every item and is slow for long lists; usecollections.deque. - Calling
remove()without checking. Guard withif x in items:.
Practice Exercises
Exercise 1. Sort ["kiwi", "fig", "banana"] from shortest to longest word.
Show answer
print(sorted(["kiwi", "fig", "banana"], key=len)) # ['fig', 'kiwi', 'banana']
Exercise 2. How many times does 3 appear in [3, 1, 3, 3, 2]?
Show answer
[3, 1, 3, 3, 2].count(3) returns 3.
Exercise 3. Empty a list without creating a new one.
Show answer
Call items.clear(). Other names that point to the same list will see it empty too.
Frequently Asked Questions
Why does sort() return None?
It changes the list in place. Returning None reminds you that no new list was made. Use sorted() when you need a new sorted list.
How do I sort a list of numbers from largest to smallest?
Use nums.sort(reverse=True) or sorted(nums, reverse=True).
What is the fastest way to remove duplicates from a list?
list(dict.fromkeys(items)) removes duplicates and keeps the original order.
Summary
- Most list methods change the list and return
None;pop(),index(),count()andcopy()return values. - Use
keyto sort by your own rule andsorted()to keep the original list. copy()is shallow; usecopy.deepcopy()for nested lists.append()pluspop()makes a stack.
