Python’s list is a mutable sequence with a small, fixed set of methods. The key
thing to know is which ones mutate in place (and return None) versus which
ones return a value. This is a searchable offline reference.
How it works
Each method is flagged as in-place or returns a value:
- In-place, returns
None—append,extend,insert,remove,sort,reverse,clear. These change the list itself; assigning their result (x = x.sort()) is a classic bug that storesNone. - Returns a value —
popreturns the removed element,indexreturns a position,countreturns a tally,copyreturns a new list.
The single most common mistake is items = items.sort(). Use items.sort() to
sort in place, or sorted(items) for a new sorted list.
append vs extend
a = [1, 2]
a.append([3, 4]) # a -> [1, 2, [3, 4]] (one nested element)
b = [1, 2]
b.extend([3, 4]) # b -> [1, 2, 3, 4] (concatenated)
Notes
sortandreversemutate in place and returnNone; their non-mutating counterparts are the built-inssorted()andreversed().pop()with no argument removes and returns the last element;pop(0)removes the first (which is O(n) — prefercollections.dequefor queues).copy()is a shallow copy — nested mutable objects are shared.- This reference covers all standard
listmethods;len,sorted,reversedare built-in functions, not list methods.