Python Reference Sheet

Quick Reference in IDE

dir(list)          # show all methods on a type
help(list.pop)     # show what a method does

Class Template

class MyClass:
    def __init__(self):
        self.data = {}        # always use self.

    def add(self, key, value):
        self.data[key] = value

    def remove(self, key):
        if key in self.data:
            del self.data[key]
            return True
        return False

Dict Operations

d = {'a': 1, 'b': 2}
d['a']                    # access — KeyError if missing
d.get('a', None)          # safe access — returns None if missing
d.get('c', 0)             # safe access — returns 0 if missing
d['c'] = 3                # add/update
del d['a']                # delete
'a' in d                  # check key exists
'x' in d.values()         # check value exists
d.keys()                  # all keys
d.values()                # all values
d.items()                 # all (key, value) pairs

Frequency Counting Pattern

# standard pattern
d[key] = d.get(key, 0) + 1

# accumulating totals
d[key] = d.get(key, 0) + amount

# verbose equivalent
if key not in d:
    d[key] = 1
else:
    d[key] += 1

Nested Dict Navigation

# walk a path like "/home/docs/file.txt"
def _navigate(self, path):
    parts = path.strip('/').split('/')
    current = self.fs
    for part in parts[:-1]:
        if part not in current or isinstance(current[part], str):
            return None, None
        current = current[part]
    return current, parts[-1]

# usage — all operations use the same pattern
parent, name = self._navigate(path)
parent[name] = value          # add
del parent[name]              # delete
return parent[name]           # get
name in parent                # exists

# walk full path creating dicts along the way
parts = path.strip('/').split('/')
current = self.fs
for part in parts:
    if part not in current:
        current[part] = {}
    current = current[part]

Dict Unpacking

product = {'name': 'laptop', 'price': 1200}

{**product}                          # copy
{**product, 'price': 999}            # copy with updated field
{**product, 'stock': 50}             # copy with new field

List Operations

lst = [1, 2, 3]
lst.append(4)              # add to end
lst.remove(2)              # remove first occurrence of value
lst.pop()                  # remove and return last — returns 3
lst.pop(0)                 # remove and return first
del lst[1]                 # delete by index
len(lst)                   # length
3 in lst                   # membership check
lst.insert(0, 'x')        # insert at index

Set Operations

s = {1, 2, 3}
s.add(4)                   # add — no duplicates
s.discard(2)               # remove (no error if missing)
s.remove(2)                # remove (KeyError if missing)
2 in s                     # O(1) membership check
list(s)                    # convert to list

String Operations

s = "hello world"
s.split()                  # ['hello', 'world'] — splits on whitespace
s.split(',')               # split on specific char
' '.join(['a', 'b'])       # 'a b' — join list into string
s.strip()                  # remove leading/trailing whitespace
s.lower()                  # lowercase
s.upper()                  # uppercase
s.replace('old', 'new')    # replace
f"value is {x}"            # f-string formatting

Slicing

s = "abcdef"
s[0:3]       # "abc"         — start to index 2
s[2:]        # "cdef"        — index 2 to end
s[:3]        # "abc"         — start to index 2
s[-1]        # "f"           — last element
s[-2:]       # "ef"          — last 2 elements
s[:-1]       # "abcde"       — everything except last
s[::-1]      # "fedcba"      — reversed
s[::2]       # "ace"         — every 2nd element

Sorting

# ascending
data.sort(key=lambda x: x['value'])

# descending
data.sort(key=lambda x: -x['value'])

# descending with alphabetical tie-break
data.sort(key=lambda x: (-x['value'], x['name']))

# sorted() returns new list (original unchanged)
result = sorted(data, key=lambda x: x['value'])

# top n after sorting
result = sorted(data, key=lambda x: -x['value'])[:n]

# max/min by key
max(data, key=lambda x: x['value'])

# key with highest value in a dict
max(d, key=d.get)

Filter, Map, Project

# filter — keep items matching condition
[x for x in data if x['age'] > 21]
list(filter(lambda x: x['age'] > 21, data))

# project — extract specific fields
[x['name'] for x in data]
list(map(lambda x: x['name'], data))

# map — transform each item
[x * 2 for x in nums]
list(map(lambda x: x * 2, nums))

# filter + project combined
[x['name'] for x in data if x['age'] > 21]

# filter + transform
list(map(
    lambda product: {**product, 'price': product['price'] * 1.10},
    filter(lambda product: product['price'] > 100, products)
))

List Comprehensions

[item for item in data if condition]         # filter
[item * 2 for item in data if item > 0]      # filter + transform
{k: v for k, v in d.items() if v > 10}       # dict comprehension
[item for sublist in lists for item in sublist]  # flatten nested

Queue and Stack

# queue — FIFO (first in, first out)
from collections import deque
q = deque()
q.append('first')         # add to back
q.popleft()               # remove from front
list(q)                   # convert deque to list

# stack — LIFO (last in, first out)
stack = []
stack.append('first')     # push
stack.pop()               # pop last item

Useful Builtins

len(data)                  # length
max(data)                  # maximum
min(data)                  # minimum
sum(data)                  # sum
sorted(data)               # sorted copy
enumerate(data)            # (index, value) pairs
zip(list1, list2)          # pair elements
range(n)                   # 0 to n-1
range(start, stop)         # start to stop-1
range(start, stop, step)   # with step
isinstance(x, str)         # type check
isinstance(x, dict)        # type check

Counter (frequency counting shortcut)

from collections import Counter
counts = Counter(['a', 'b', 'a', 'c', 'a'])
# Counter({'a': 3, 'b': 1, 'c': 1})
counts.most_common(2)      # [('a', 3), ('b', 1)]

Error Handling

try:
    result = risky_operation()
except KeyError as e:
    print(f"Key not found: {e}")
except Exception as e:
    print(f"Error: {e}")

Datetime

from datetime import datetime

# parse ISO timestamp string
dt = datetime.fromisoformat("2026-01-15T08:30:00")

# difference in days
start = datetime.fromisoformat(start_date)
end = datetime.fromisoformat(end_date)
total_days = (end - start).days

# ISO format strings compare correctly as strings
"2026-01-01" < "2026-06-15"   # True

Division

7 / 2      # 3.5  — true division (float)
7 // 2     # 3    — floor division (int)
7 % 2      # 1    — modulo (remainder)

Common Patterns

# REUSE YOUR OWN METHODS!!
total = self.get_total(order_id)    # don't recalculate

# safe nested access
self.data.get(user_id, {}).get(item_id, None)

# initialize nested structure
if user_id not in self.data:
    self.data[user_id] = {}
self.data[user_id][key] = value

# validate against allowed values
valid = {'pending', 'active', 'closed'}
if status not in valid:
    return False

Priority Ordering Pattern

# custom sort order using a dict
priority_order = {'critical': 0, 'high': 1, 'medium': 2, 'low': 3}
result.sort(key=lambda x: priority_order[x['priority']])

Validation Pattern

valid = {'low', 'medium', 'high', 'critical'}
if value not in valid:
    return False

Set for Unique Counting

users = set()
for item in data:
    users.add(item['user'])
count = len(users)

Common Return Pattern

# don't forget both paths
def do_thing(self, id):
    if id not in self.data:
        return False
    # do the work
    return True    # <-- don't forget this