Python List Methods Cheat Sheet
1 · The lesson
readA list holds several values in order, such as prices, names or scores. You can change a list after you create it: add items, remove them, sort them. A list may hold duplicates and a mix of types. This page shows the list tools you will use most, with examples you can run. For the full tutorial, see Lists.
1. Create a list
a = [1, "a", "a"] # items can be of different types and can repeat b = [] # an empty list list("abc") # ['a', 'b', 'c'] (turns anything you can loop over into a list) list(range(4)) # [0, 1, 2, 3] [0] * 3 # [0, 0, 0] [[0] * 3 for _ in range(2)] # [[0, 0, 0], [0, 0, 0]] (a grid: makes a new inner list for each row)
2. Index and slice
Each item has a position number, called an index. The first item is at index 0, and negative numbers count from the end. A slice xs[start:stop] gives a new list from start up to, but not including, stop.
xs = [10, 20, 30, 40, 50] xs[0] # 10 (the first item) xs[-1] # 50 (the last item) xs[1:4] # [20, 30, 40] xs[-2:] # [40, 50] (the last two items) xs[::2] # [10, 30, 50] (every second item) xs[::-1] # [50, 40, 30, 20, 10] (a reversed copy) xs[3:99] # [40, 50] (a slice past the end is fine; xs[99] would be an error) len(xs) # 5
You can also assign to an index or a slice. When you assign to a slice, the new part can be longer or shorter than the part it replaces.
xs[0] = 99 # [99, 20, 30, 40, 50] xs[1:3] = [0] # [99, 0, 40, 50]
setup added so this can run · re-runs 1 earlier block on this page first
xs = ["alpha", "beta", "gamma"] # Earlier blocks on this page that this one builds on, re-run quietly first. _pm_earlier = [ 'xs = [10, 20, 30, 40, 50]\nxs[0] # 10 (the first item)\nxs[-1] # 50 (the last item)\nxs[1:4] # [20, 30, 40]\nxs[-2:] # [40, 50] (the last two items)\nxs[::2] # [10, 30, 50] (every second item)\nxs[::-1] # [50, 40, 30, 20, 10] (a reversed copy)\nxs[3:99] # [40, 50] (a slice past the end is fine; xs[99] would be an error)\nlen(xs) # 5', ] def _pm_run_earlier(_srcs, _g): import sys as _s, io as _io, warnings as _w for _src in _srcs: _o, _e = _s.stdout, _s.stderr _s.stdout = _s.stderr = _io.StringIO() try: with _w.catch_warnings(): _w.simplefilter('ignore') exec(compile(_src, '<earlier block>', 'exec'), _g) except (Exception, SystemExit): pass finally: _s.stdout, _s.stderr = _o, _e if 'matplotlib.pyplot' in _s.modules: _s.modules['matplotlib.pyplot'].close('all') # their plots belong to their own blocks _pm_run_earlier(_pm_earlier, globals()) del _pm_earlier, _pm_run_earlier
3. Add items
append() adds one item to the end. extend() adds each item of another list. Both change the list itself and return None. The + operator builds a new list and leaves the old ones as they were.
| Code | What it does | Changes the list? |
|---|---|---|
xs.append(x) | Adds one item to the end | Yes |
xs.extend(other) | Adds each item of other to the end | Yes |
xs.insert(i, x) | Puts x before index i | Yes |
xs += other | The same as extend() | Yes |
xs + other | Builds a new, joined list | No |
xs = [1, 2] xs.append(3) # [1, 2, 3] xs.extend([4, 5]) # [1, 2, 3, 4, 5] xs.insert(0, 0) # [0, 1, 2, 3, 4, 5] [1, 2] + [3] # [1, 2, 3]
4. Remove items
remove() deletes by value. pop() and del delete by position.
| Code | What it does | Error when |
|---|---|---|
xs.remove(x) | Removes the first item equal to x | ValueError if x is not in the list |
xs.pop() | Removes the last item and returns it | IndexError if the list is empty |
xs.pop(i) | Removes the item at index i and returns it | IndexError if i is too big |
del xs[i] | Removes the item at index i | IndexError if i is too big |
del xs[i:j] | Removes a slice | never |
xs.clear() | Removes everything | never |
xs = [1, 2, 3, 2, 5] xs.remove(2) # [1, 3, 2, 5] (only the first 2 is removed) xs.pop() # 5 xs.pop(0) # 1 del xs[0] # [2] xs.clear() # []
5. Search and count
Lists have no find() method. index() raises a ValueError when the value is missing, so check with in first.
xs = [3, 1, 2, 1] 2 in xs # True xs.index(1) # 1 (the index of the first 1) xs.count(1) # 2 min(xs), max(xs), sum(xs) # (1, 3, 7) any(x > 2 for x in xs) # True (at least one item is bigger than 2) all(x > 0 for x in xs) # True (every item is bigger than 0)
6. Sort and reverse
sorted(xs) returns a new sorted list and leaves xs as it was. xs.sort() sorts the list itself and returns None. The key argument takes a function: Python sorts the items by what that function returns.
xs = [3, 1, 2] sorted(xs) # [1, 2, 3] sorted(xs, reverse=True) # [3, 2, 1] xs # [3, 1, 2] (xs has not changed) xs.sort() # [1, 2, 3] xs.reverse() # [3, 2, 1] list(reversed(xs)) # [1, 2, 3] sorted(["bb", "a", "ccc"], key=len) # ['a', 'bb', 'ccc'] (sorted by length, shortest first) scores = [("Grace", 88), ("Ada", 95), ("Linus", 88)] sorted(scores, key=lambda p: p[1]) # [('Grace', 88), ('Linus', 88), ('Ada', 95)]
lambda p: p[1] is a small function with no name. It returns the second item of each pair, so the scores are sorted by the number. The sort is stable: items with the same key keep their original order, which is why Grace still comes before Linus.
7. Copy a list
b = a does not copy anything: it gives the same list a second name. a.copy(), a[:] and list(a) make a shallow copy: a new outer list, but any lists inside it are still shared. copy.deepcopy() copies the inner lists too.
import copy a = [1, [2, 3]] b = a.copy() b[1].append(4) a # [1, [2, 3, 4]] (the inner list is shared) c = copy.deepcopy(a) c[1].append(5) a # [1, [2, 3, 4]] (a did not change this time)
8. Loop over a list
enumerate() gives you the index with each item. zip() goes through two lists side by side and stops at the end of the shorter one.
names, scores = ["Ada", "Grace"], [95, 88] for i, name in enumerate(names, 1): # start counting from 1 print(i, name) for name, score in zip(names, scores): print(name, score) dict(zip(names, scores)) # {'Ada': 95, 'Grace': 88}
1 Ada 2 Grace Ada 95 Grace 88
9. Comprehensions
A list comprehension builds a new list from a loop in one line. See the Comprehensions cheat sheet for more.
nums = [3, -1, 4] [n * 2 for n in nums] # [6, -2, 8] [n for n in nums if n > 0] # [3, 4] (to keep some items, put the if at the end) [n if n > 0 else 0 for n in nums] # [3, 0, 4] (to choose a value, put if/else first) grid = [[1, 2], [3, 4]] [x for row in grid for x in row] # [1, 2, 3, 4] (one flat list; the loops are in the same order as nested for loops) list(map(str, nums)) # ['3', '-1', '4'] (converts every item to a string)
10. Useful patterns
xs = [1, 2, 3, 4, 5] sum(xs) / len(xs) # 3.0 (the average) [xs[i:i + 2] for i in range(0, len(xs), 2)] # [[1, 2], [3, 4], [5]] (splits the list into groups of 2) list(dict.fromkeys([3, 1, 3, 2])) # [3, 1, 2] (remove duplicates and keep the order) xs[0], xs[-1] = xs[-1], xs[0] # swaps the first and last items xs # [5, 2, 3, 4, 1]
Common mistakes
Assigning the result of sort(). sort() returns None, so xs = xs.sort() replaces your list with None. Use xs.sort() on its own line, or xs = sorted(xs).
Thinking b = a makes a copy. Both names point to the same list, so a change through one name shows through the other:
a = [1, 2] b = a b.append(3) a # [1, 2, 3]
Use b = a.copy() when you want a separate list.
Building a grid with *. [[0] * 2] * 2 repeats one inner list, so every row is the same list:
grid = [[0] * 2] * 2 grid[0][0] = 9 grid # [[9, 0], [9, 0]] grid = [[0] * 2 for _ in range(2)] grid[0][0] = 9 grid # [[9, 0], [0, 0]]
Removing items while you loop over the same list. The loop skips items. Loop over a copy (for x in xs[:]) or build a new list with a comprehension:
ys = [1, 2, 2, 3] ys = [y for y in ys if y != 2] ys # [1, 3]
Using append() when you meant extend(). ys.append([4, 5]) adds the whole list as one item. ys.extend([4, 5]) adds each item.
Indexing one past the end. The last index is len(xs) - 1, so xs[len(xs)] raises IndexError: list index out of range (full error page).
Sorting mixed types. sorted([3, "a"]) raises TypeError, because Python cannot say whether a number comes before a string.
A list as a default argument. Python creates the default list once, and every call shares that same list. Use None as the default and make a new list inside the function:
def add(x, items=None): if items is None: # make a new list on each call items = [] items.append(x) return items add(1), add(2) # ([1], [2])
See also
Practice this
on practicepython.inShort exercises that run in your browser and tell you what your code did, as well as whether a test passed.
Found this useful? Share it with a friend who’s learning Python.