List Methods
List methods reference. Lists are mutable — most methods change the list in place and return None.
Add
| Method | What it does |
|---|---|
append(x) | Add x to the end. |
extend(iter) | Append each item from iter. |
insert(i, x) | Insert x at index i. |
Remove
| Method | What it does |
|---|---|
remove(x) | Remove first occurrence of x; raises ValueError if missing. |
pop(i=-1) | Remove and return item at i (default last). |
clear() | Remove everything. |
del lst[i] | Remove by index (statement, not method). |
Search
| Method | What it does |
|---|---|
index(x, start=, stop=) | First index of x; ValueError if missing. |
count(x) | How many. |
x in lst | Membership. |
Reorder
| Method | What it does |
|---|---|
sort(key=, reverse=) | Sort in place. |
reverse() | Reverse in place. |
sorted(lst) | NEW sorted list — does not mutate. |
Copy
| Method | What it does |
|---|---|
copy() | Shallow copy. |
lst[:] | Also shallow copy. |
copy.deepcopy(lst) | Deep copy of nested structures. |
Slicing
PYTHON
lst[2:5] # items 2 through 4 lst[:3] # first three lst[-3:] # last three lst[::2] # every other lst[::-1] # reversed
Build with comprehensions
PYTHON
squares = [n * n for n in range(10)] evens_sqrd = [n * n for n in range(10) if n % 2 == 0] matrix = [[c for c in 'abc'] for _ in range(3)]
Tip:
sort mutates and returns None. sorted returns a new list. nums.sort().reverse() is a common bug because sort() returns None.Example
Example
a = [3, 1, 2] a.append(4) a.sort() print(a) print(a.index(2)) a.pop() print(a) print([x * 2 for x in a])Try it Yourself »
Exercise
Append every item of an iterable to the list.
a.
(b)
Six letters.
Discussion
Loading…