Skip to main content

list

Dynamic array: O(1) indexing and amortized O(1) append/pop at the end, O(n) insert/delete elsewhere. The default container for arrays, stacks, DP tables and grids. Use deque instead when you need fast pops from the front.

Syntax​

nums = [3, 1, 4, 1, 5]
empty = []
zeros = [0] * 5 # -> [0, 0, 0, 0, 0]
chars = list("abc") # -> ['a', 'b', 'c']
r = list(range(3)) # -> [0, 1, 2]

Indexing​

nums = [3, 1, 4, 1, 5]
nums[0] # -> 3, O(1)
nums[-1] # -> 5, last
nums[-2] # -> 1, second to last
len(nums) # -> 5, O(1)

Slicing (always a copy, O(k))​

nums = [0, 1, 2, 3, 4, 5]
nums[1:4] # -> [1, 2, 3] (end exclusive)
nums[:3] # -> [0, 1, 2]
nums[3:] # -> [3, 4, 5]
nums[::2] # -> [0, 2, 4] step 2
nums[::-1] # -> [5, 4, 3, 2, 1, 0] reversed copy
nums[-3:] # -> [3, 4, 5] last 3
nums[1:3] = [9, 9, 9] # slice assignment can resize

Methods and complexity​

a = [1, 2, 3]
a.append(4) # O(1) amortized
a.pop() # O(1), removes and returns last -> 4
a.pop(0) # O(n), shifts everything -> 1
a.insert(0, 7) # O(n)
a.extend([5, 6]) # O(k)
a.remove(5) # O(n), first occurrence; ValueError if missing
a.index(3) # O(n); ValueError if missing
a.count(7) # O(n)
a.reverse() # O(n), in place
del a[0] # O(n)
a.clear()

Membership is O(n)​

5 in nums # O(n) linear scan
seen = set(nums) # convert once if checking repeatedly
5 in seen # O(1) average

As a stack​

stack = []
stack.append(1) # push
stack.append(2)
stack[-1] # -> 2, peek
stack.pop() # -> 2, pop
if not stack: # empty check
...

sort vs sorted​

nums = [3, 1, 2]
nums.sort() # in place, returns None, O(n log n)
nums.sort(reverse=True)
new = sorted(nums) # new list, original unchanged
words = ["bb", "a", "ccc"]
words.sort(key=len) # -> ['a', 'bb', 'ccc']
pairs = [(1, "b"), (1, "a"), (0, "z")]
pairs.sort(key=lambda p: (p[0], p[1])) # multi-key
# Sort is stable (Timsort)

Common built-ins​

sum(nums), min(nums), max(nums)
max(words, key=len)
list(reversed(nums))
list(enumerate(nums))

2D grid​

rows, cols = 3, 4
grid = [[0] * cols for _ in range(rows)] # NOT [[0] * cols] * rows
grid[1][2] = 5
R, C = len(grid), len(grid[0])
dp = [[0] * (cols + 1) for _ in range(rows + 1)] # DP table with padding

Docs​