Skip to content
  • Lists & Tuples · Python

Lists & Tuples

LearnViaNotes @learnvianotes· 2 min read

list is a mutable, ordered, dynamic array. tuple is its immutable sibling — lighter, hashable, and used for fixed records.

Core operations & complexity

OperationExampleTime
Index / assignxs[i], xs[i] = vO(1)
Append / pop from endxs.append(v), xs.pop()O(1) amortised
Insert / pop at frontxs.insert(0, v), xs.pop(0)O(n) — use deque
Searchv in xs, xs.index(v)O(n)
Slicexs[a:b]O(b − a)
Sortxs.sort(), sorted(xs)O(n log n) — Timsort, stable
Extendxs.extend(ys), xs + ysO(len(ys))
Python
xs = [5, 2, 9]
xs.append(1)
xs.extend([7, 3])
xs.insert(1, 4)
print(xs)                       # [5, 4, 2, 9, 1, 7, 3]
print(xs.pop(), xs.pop(0))      # 3 5
xs.remove(9)                    # removes the first 9 (ValueError if absent)
print(sorted(xs), xs[::-1])     # [1, 2, 4, 7] [7, 1, 2, 4]

sort() vs sorted()

Python
people = [("Ravi", 30), ("Asha", 25), ("Kiran", 30)]
print(sorted(people, key=lambda p: p[1]))
# [('Asha', 25), ('Ravi', 30), ('Kiran', 30)]   ← stable: Ravi stays before Kiran
print(sorted(people, key=lambda p: (-p[1], p[0])))
# [('Kiran', 30), ('Ravi', 30), ('Asha', 25)]   ← age desc, then name asc

Copies: aliasing, shallow, deep

Python
import copy
grid = [[0, 0], [0, 0]]
alias = grid                 # same list
shallow = grid[:]            # new outer list, same inner lists
deep = copy.deepcopy(grid)   # everything copied
grid[0][0] = 9
print(alias[0][0], shallow[0][0], deep[0][0])   # 9 9 0
Python
bad = [[0] * 3] * 3
bad[0][0] = 1
print(bad)                              # [[1, 0, 0], [1, 0, 0], [1, 0, 0]]
good = [[0] * 3 for _ in range(3)]
good[0][0] = 1
print(good)                             # [[1, 0, 0], [0, 0, 0], [0, 0, 0]]

Tuples, packing & unpacking

Python
point = (3, 4)
x, y = point                    # unpacking
a, b = 1, 2
a, b = b, a                     # swap without a temp variable
first, *middle, last = [1, 2, 3, 4, 5]
print(x, y, a, b)               # 3 4 2 1
print(first, middle, last)      # 1 [2, 3, 4] 5
single = (42,)                  # the comma makes the tuple, not the parentheses
print(type(single).__name__)    # tuple
listtuple
MutableYesNo
Hashable (dict key / set item)NoYes, if its items are hashable
Memory / speedSlightly largerSmaller, slightly faster to create
Use forCollections that grow and changeFixed records: coordinates, DB rows, dict keys

Named tuples

Python
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x + p.y, p)          # 7 Point(x=3, y=4)

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report