Python Cheatsheet



Common third-party library references:


Python Documentation - Built-In Functions, Built-In Exceptions
Python Documentation - functools, itertools, heapq

import functools, itertools, heapq

map(lambda x: x * 2, myiterable) # Returns an iterator
functools.reduce(lambda acc, cur: acc * cur, myiterable, initializer=1) # aka fold/accumulate
itertools.accumulate(myiterable, lambda acc, cur: acc * cur, initial=1) # Returns an iterator
filter(lambda x: x > 0, myiterable) # Returns an iterator

# `heapq` implements some general-purpose functions that aren't just heap operations
heapq.merge(*myiterables, key=None, reverse=False) # Merge multiple sorted iterables into one sorted iterable
heapq.nlargest(n, myiterable, key=None)  # Returns a list. For large n, prefer to just use sorted().
heapq.nsmallest(n, myiterable, key=None) # Returns a list. For large n, prefer to just use sorted().

raise RuntimeError("your error description")
raise NotImplementedError("your error description")

# These take iterables and return iterators.
zip([1, 2, 3], [a, b, c], strict=True) # (1, a), (2, b), (3, c)   # strict=True throws ValueError if iterable "lengths" mismatch
zip([1, 2, 3], [x, y]) # (1, x), (2, y)   # strict=False is by default. Takes the shortest "length".
itertools.zip_longest("ABCD", "xy", fillvalue="-") # ("A", "x"), ("B", "y"), ("C", "-"), ("D", "-")


Python Documentation - Built-In Functions
Python Documentation - math

import math

math.inf # Floating point positive infinity. Use -math.inf for negative.

base ** exponent # Use this if you're not sure. Lets the interpreter optimize.
pow(base, exponent, mod=None) # Efficient implementation of (base ** exponent) % mod
math.pow(base, exponent) # Floating point power, follows "IEEE 754 standard as far as possible"
# See `math` for specialized exponential functions like math.exp()

(x, y) = divmod(a, b) # for integers, it's the same as (a // b, a % b)


list and tuple

Unless otherwise stated, all non-mutating list operations shown also work with tuple.

Python Documentation - list, tuple, range

# Push/pop/peek at the back

# Push/pop/peek at the front
mylist.insert(0, x)

mylist[startInclusive:endExclusive:step] # slice


Python Documentation - dict

for k, v in mydict.items(): print(k, v)
for k in mydict: print(k)
for v in mydict.values(): print(v)

# All of these try to return the value associated with key k, but behave a bit differently
mydict[k]                     # Raises KeyError if key is missing
mydict.get(k, default)        # Returns default if key is missing
mydict.pop(k)                 # Also deletes key. Raises KeyError if key is missing.
mydict.pop(k, default)        # Instead returns default if key is missing
mydict.setdefault(k, default) # Assigns `mydict[k] = default` if key is missing

mydict.popitem() # Pop a (key, value) pair in LIFO order (Python 3.7)


Python Documentation - set

myset = set() # empty set, can't use {} because {} is a dict
myset = {1, 2, 3} # pre-filled set, can use {} without colon
myset.remove(x)  # Raises KeyError if value is missing
myset.discard(x) # Fails silently

# Implemented operator overloads:
# ==  !=  >=  <=  >  <  |  &  -  ^  |=  &=  -=  ^=

set1.isdisjoint(set2) # True if both sets have nothing in common.

For multisets, see collections.Counter.


Python Documentation - str

", ".join(myiterable) # ["foo", "bar", "baz"] --> "foo, bar, baz"

More Data Structures

Python Documentation - collections, heapq

import collections, heapq

# defaultdict (inherits `dict`)
mydict = collections.defaultdict(list)

# Counter / Multiset (inherits `dict`)
cnt = collections.Counter(myiterable)
cnt.elements() # Returns an iterator over each element, with repeats
# Implemented operator overloads for multiset operations:
# ==  !=  >=  <=  >  <  |  &  +  -  |=  &=  +=  -= 

# Deque / Double-ended Queue
dq = collections.deque(myiterable) # fast double-ended pop/push
# All of these ops modify the deque in-place
dq.append(x)     # back
dq.appendleft(x) # front
dq.pop()     # back
dq.popleft() # front
dq.extend(myiterable)     # back
dq.extendleft(myiterable) # front
dq.rotate(2) # [1,2,3,4,5] --> [4,5,1,2,3]; negative numbers go the other way

# Heap / Priority Queue
# `heapq` effectively implements a min-heap
pq = [a, b, c, d, e] # We can initialize in any order...
heapq.heapify(pq) # ...because heapify() will transform it into a heap in O(n) time.
pq[0] # Peek at the smallest item
heapq.heappush(pq, x)
heapq.heappop(pq) # pop the smallest item
heapq.heappushpop(pq, x) # Effectively a push followed by a pop
heapq.heapreplace(pq, x) # Effectively a pop followed by a push

# namedtuple (inherits `tuple`)
Point = namedtuple('Point', ['x', 'y'])
p = Point(11, 22)
p = Point(x=11, y=22) # kwargs also works
x = p.x # field accessible by name
# namedtuples still work like regular tuples
x = p[0] # same as p.x
(x, y) = p # unpackable

System API

Python Documentation - os, sys

# TODO: examples?

The Module System

import datetime

from datetime import timedelta, date

# This one imports everything except names starting in `_`
from datetime import *

import datetime as foobar

from datetime import timedelta as foobar, date

# TODO: Include good relative imports examples?

If a module can be executed as a script, it should include:

#!/usr/bin/env python3


if __name__ == "__main__":
    # YOUR DRIVER CODE HERE (the sys.argv stuff is just an example)
    import sys

Basic Recipes

Starting Templates


#!/usr/bin/env python3

if __name__ == "__main__":
    print("Hello World!")

Competitive programming:

#!/usr/bin/env python3

n = input()
nums = [int(s) for s in input().strip().split()]
words = [s.strip() for s in input().strip().split()]
#!/usr/bin/env python3

from sys import stdin

n = int(stdin.readline())
nums = [int(s) for s in stdin.readline().strip().split()]
words = [s.strip() for s in stdin.readline().strip().split()]

nums2 = [[int(x) for x in s.strip().split()] for s in stdin.readlines()]


Python lacks sorted associative containers like C++‘s std::set and std::map. As a workaround, Leetcode supplies the sortedcontainers library to use on the platform (as mentioned here).


from collections import defaultdict

class Trie:
    __slots__ = ["_root"]

    def __init__(self):
        op = lambda: defaultdict(op)
        self._root = op()

    def add(self, s):
        reduce(lambda cur, c: cur[c], s, self._root)[""] = True

    def has(self, s):
        cur = self._root
        for c in s:
            if c not in cur:
                return False
            cur = cur[c]
        return "" in cur

    def starts_with(self, prefix):
        cur = self._root
        for c in prefix:
            if c not in cur:
                return False
            cur = cur[c]
        return True


[DRAFT] Official Docs - Curated Index

(This section is still under consideration. I still don’t know how I feel about including it. But for now, here’s my current work-in-progress!)