Python List Methods
Python lists come with a set of built-in methods for adding, removing, searching, ordering, and copying their contents.
The built-in list methods
Because lists are mutable, most of their methods change the list in place rather than returning a new one. Knowing which methods modify the list and which return a value helps you avoid common mistakes, such as assigning the None result of an in-place method back to your variable.
Searching and counting
The index() method tells you where a value first appears, while count() reports how many times it occurs. These are read-only methods, so they never alter the list itself.
index() and count()
letters = ["a", "b", "a", "c", "a"]
print(letters.index("b"))
print(letters.count("a"))letters.index('b') returns 1 because 'b' first appears at index 1, and letters.count('a') returns 3 because 'a' occurs three times.
Sorting and reversing
sort() and reverse()
nums = [3, 1, 4, 1, 5]
nums.sort()
print(nums)
nums.sort(reverse=True)
print(nums)sort() rearranges the list ascending into [1, 1, 3, 4, 5], and sort(reverse=True) then orders it descending into [5, 4, 3, 1, 1]. Both change the list in place and return None.
- In-place methods (append, sort, reverse, remove) return None, so do not assign their result back.
- Use sorted(list) instead of list.sort() when you want a new sorted list and need to keep the original order.
- index() and remove() raise errors if the value is missing, so check with 'in' first when unsure.