List Methods
Core Methods
Lists have many built-in methods for adding, removing, searching, and modifying items. The table summarizes the most common ones.
Method | Description | Example |
---|---|---|
append(x) | Add x to the end of the list | lst.append(4) |
extend(iter) | Add all items from an iterable to the list | lst.extend([4, 5]) |
insert(i, x) | Insert x at index i | lst.insert(1, 'a') |
remove(x) | Remove the first occurrence of x | lst.remove(2) |
pop([i]) | Remove and return item at index i (last by default) | x = lst.pop() |
clear() | Remove all items from the list | lst.clear() |
index(x) | Return index of the first occurrence of x | i = lst.index('a') |
count(x) | Return the number of occurrences of x | n = lst.count(1) |
sort() | Sort the list in place | lst.sort() |
reverse() | Reverse the list in place | lst.reverse() |
copy() | Return a shallow copy of the list | new = lst.copy() |
Method Chaining
Most list methods that modify the list return None, so they cannot be chained directly. To achieve chaining-like behavior, perform operations step by step or wrap them in a helper function.
Example
# Attempting to chain (will fail)
result = [1, 2, 3].copy().append(4).pop() # AttributeError
# Correct approach
def chainable(lst):
lst = lst.copy()
lst.append(4)
return lst.pop()
print(chainable([1, 2, 3]))
Output
4
ℹ️ Note: Mutating methods return None to avoid ambiguity, encouraging clearer code.
Special Method Implementations
Lists implement several special methods that integrate with Python operators. These make lists compatible with `in`, `+`, and `*` operators.
Example
# __contains__ for 'in' operator
print(3 in [1, 2, 3]) # True
# __add__ for + operator
print([1, 2] + [3, 4]) # [1, 2, 3, 4]
# __mul__ for repetition
print([0] * 5) # [0, 0, 0, 0, 0]
Output
True [1, 2, 3, 4] [0, 0, 0, 0, 0]