Python Cheatsheet
Lists and Tuples
Use this Python reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
List Creation
lst = [] # empty lst = [1, 2, 3] lst = list() # empty from constructor lst = list("abc") # ['a', 'b', 'c'] lst = list(range(5)) # [0, 1, 2, 3, 4] lst = [0] * 5 # [0, 0, 0, 0, 0] lst = [[0] * 3 for _ in range(3)] # 3x3 matrix (correct way) # BAD: [[0]*3]*3 — rows share the same list object
Indexing and Slicing
lst = [10, 20, 30, 40, 50] lst[0] # 10 (first) lst[-1] # 50 (last) lst[-2] # 40 (second-to-last) # Slicing: lst[start:stop:step] — stop is exclusive lst[1:3] # [20, 30] lst[:3] # [10, 20, 30] lst[2:] # [30, 40, 50] lst[:] # [10, 20, 30, 40, 50] (shallow copy) lst[::2] # [10, 30, 50] (every other) lst[::-1] # [50, 40, 30, 20, 10] (reverse) lst[1:-1] # [20, 30, 40] # Assignment via slice lst[1:3] = [99, 88] # replace elements lst[::2] = [0, 0, 0] # replace every other lst[1:1] = [5, 6] # insert without removing
List Methods
| Method | Description | Example |
|---|---|---|
append(x) | Add x to end | lst.append(4) |
extend(iter) | Add all items from iterable | lst.extend([4, 5]) |
insert(i, x) | Insert x before index i | lst.insert(0, 99) |
remove(x) | Remove first occurrence of x | lst.remove(2) |
pop(i=-1) | Remove and return item at i | lst.pop() / lst.pop(0) |
clear() | Remove all items | lst.clear() |
index(x, start, stop) | Index of first x | lst.index(3) |
count(x) | Count occurrences of x | lst.count(2) |
sort(key, reverse) | Sort in place | lst.sort() / lst.sort(reverse=True) |
reverse() | Reverse in place | lst.reverse() |
copy() | Shallow copy | lst2 = lst.copy() |
# sort vs sorted lst.sort() # in-place, returns None new = sorted(lst) # returns new list, lst unchanged sorted(lst, key=len, reverse=True) # by length, descending sorted(lst, key=lambda x: x.lower()) # Removing duplicates (preserving order) seen = set() unique = [x for x in lst if not (x in seen or seen.add(x))] # Or simpler (Python 3.7+ dict preserves order): unique = list(dict.fromkeys(lst))
Common Operations
# Concatenation and repetition [1, 2] + [3, 4] # [1, 2, 3, 4] [0] * 5 # [0, 0, 0, 0, 0] # Membership 3 in [1, 2, 3] # True 4 not in [1, 2, 3] # True # Length, min, max, sum len(lst) min(lst) max(lst) sum(lst) # Flattening one level nested = [[1, 2], [3, 4], [5]] flat = [x for sub in nested for x in sub] # [1, 2, 3, 4, 5] # or: import itertools flat = list(itertools.chain.from_iterable(nested)) # Check if empty if not lst: print("empty")
Copying Lists
# Shallow copy (all are equivalent) b = a[:] b = a.copy() b = list(a) # Deep copy (for nested mutable structures) import copy b = copy.deepcopy(a)
Sorting Deep Dive
data = [{"name": "Bob", "age": 25}, {"name": "Alice", "age": 30}]
# Sort by key
sorted(data, key=lambda x: x["age"])
# Multiple keys
from operator import itemgetter, attrgetter
sorted(data, key=itemgetter("age")) # single key
sorted(data, key=itemgetter("age", "name")) # multiple keys
# Objects
sorted(objects, key=attrgetter("priority"))
sorted(objects, key=attrgetter("priority", "name"))
# Stable sort — equal keys keep original relative order
# Python sort is always stable (Timsort)Stack and Queue Usage
# Stack (LIFO) — use list directly stack = [] stack.append(1) # push stack.pop() # pop from end — O(1) # Queue (FIFO) — use collections.deque for O(1) popleft from collections import deque q = deque() q.append(1) # enqueue q.popleft() # dequeue — O(1) q.appendleft(0) # prepend q.pop() # remove from right deque(maxlen=5) # fixed-size, auto-discards oldest
Tuple Creation
t = () # empty tuple t = (1,) # single-element (trailing comma required!) t = (1, 2, 3) t = 1, 2, 3 # parentheses optional t = tuple([1, 2, 3]) # from iterable t = tuple("abc") # ('a', 'b', 'c')
Tuple Operations
Tuples support all read-only list operations: indexing, slicing, in, len, min, max, sum, count, index.
t = (10, 20, 30, 20) t[0] # 10 t[-1] # 20 t[1:3] # (20, 30) t[::-1] # (20, 30, 20, 10) len(t) # 4 t.count(20) # 2 t.index(30) # 2 20 in t # True # Concatenation (1, 2) + (3, 4) # (1, 2, 3, 4) (0,) * 3 # (0, 0, 0)
Tuple Unpacking
a, b, c = (1, 2, 3) x, y = y, x # swap values # Extended unpacking (Python 3+) first, *rest = [1, 2, 3, 4] # first=1, rest=[2,3,4] *init, last = [1, 2, 3, 4] # init=[1,2,3], last=4 a, *mid, z = [1, 2, 3, 4, 5] # a=1, mid=[2,3,4], z=5 # Nested unpacking (a, b), c = (1, 2), 3 # Ignore values with _ _, second, _ = (1, 2, 3) first, *_ = [1, 2, 3, 4, 5]
Named Tuples
from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) p = Point(1, 2) p.x # 1 p.y # 2 p[0] # 1 (index still works) p._asdict() # {'x': 1, 'y': 2} p._replace(x=10) # Point(x=10, y=2) — new instance # Typed version with dataclass-like syntax (Python 3.6+) from typing import NamedTuple class Point(NamedTuple): x: float y: float z: float = 0.0 # default value
Lists vs Tuples
| Feature | list | tuple |
|---|---|---|
| Mutable | Yes | No |
| Hashable | No | Yes (if contents hashable) |
| As dict key | No | Yes |
| Memory | More | Less |
| Speed (iteration) | Slightly slower | Slightly faster |
| Use when | Need to modify | Fixed data / dict key |
# Tuples as dict keys (lists cannot be) d = {(0, 0): "origin", (1, 0): "x-axis"} d[(0, 0)] # "origin" # hash works on tuples hash((1, 2, 3)) # works hash([1, 2, 3]) # TypeError: unhashable type: 'list'