InterviewPrepKit

Home / Cheat Sheet / Algorithms & Data Structures with Python

Cheat sheet

Lists, Tuples, and Slicing

Read the full lesson →

Lists and tuples hold many ordered values under one name; slicing pulls out ranges, and aliasing is the bug to watch for.

Lists vs tuples

  • List [ ]: ordered and mutable (change, add, remove). Use when it grows, shrinks, or reorders.
  • Tuple ( ): ordered and immutable. Use for fixed groups where position has meaning ((x, y)); can be a dict key.
  • Both support indexing, negative indexing, len, slicing, for, in.
  • One-item tuple needs a trailing comma: (5,) is a tuple, (5) is an int.

Indexing and access

  • Index starts at 0; first is x[0], last is x[-1] or x[len(x)-1].
  • Out-of-range index raises IndexError; x[len(x)] is always invalid.
  • Negative indexing counts from the end: -1 last, -2 second-to-last.
  • Nested: grid[1][0] reads row 1, then its item 0.
  • Unpacking: x, y = point (names must match item count). Swap with a, b = b, a.

Operation costs (n = list length)

  • x[i] index, len(x), x.pop() (from end): O(1)
  • x.append(v): amortized O(1)
  • x.insert(i, v), x.remove(v), v in x, full for pass: O(n)
  • Slice of k items: O(k) time and space (builds a new list).
  • remove deletes only the first match and raises ValueError if absent.

Slicing: x[start:stop:step]

  • start included, stop excluded, step default 1. x[1:3] gives indices 1 and 2.
  • Omit start = from beginning; omit stop = through end; x[:] = full copy.
  • x[::2] every other item; x[::-1] reverses.
  • Out-of-range stop is forgiving: it just stops at the end.
 nums = [10, 20, 30, 40, 50]
index   0   1   2   3   4
        [10, 20, 30, 40, 50]
nums[1:3] -> [20, 30]   (1 in, 3 out)

Aliasing gotcha

  • b = a copies the reference, not the list. Both names point at one list, so a change through one shows in the other.
  • Real (shallow) copy: b = list(a) or b = a[:], O(n).
  • Shallow copy still shares inner lists; use copy.deepcopy for fully independent nested structures.
Want the full picture? The lesson has the derivations, worked examples, and diagrams this card compresses into bullets. Read the full lesson →
Report a bug