Python Cheatsheet
Resources
References:
- Python Documentation - The Python Standard Library
(docs.python.org)
- Learn X in Y minutes - Python
(learnxinyminutes.com)
Common third-party library references:
Misc.
Python Documentation - Built-In Functions, Built-In Exceptions, Data Model
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) # multiple sorted iterables --> 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", "-")
# For the other magic methods, look at the Data Model documentation.
class MyClass(MyBaseClass):
__slots__ = ("_foo",)
def __init__(self, foo):
super().__init__(foo)
self._foo = foo
x = MyClass("lmao")
Math
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)
Types
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
mylist.append(x)
mylist.pop()
mylist[-1]
# Push/pop/peek at the front
mylist.insert(0, x)
mylist.pop(0)
mylist[0]
mylist[startInclusive:endExclusive:step] # slice
dict
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)
set
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.add(x)
myset.remove(x) # Raises KeyError if value is missing
myset.discard(x) # Fails silently
myset.pop()
# Implemented operator overloads:
# == != >= <= > < | & - ^ |= &= -= ^=
set1.isdisjoint(set2) # True if both sets have nothing in common.
For multisets, see collections.Counter
.
str
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.reverse()
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
datetime.timedelta()
datetime.date.today()
from datetime import timedelta, date
timedelta()
date.today()
# This one imports everything except names starting in `_`
from datetime import *
timedelta()
date.today()
import datetime as foobar
foobar.timedelta()
foobar.date.today()
from datetime import timedelta as foobar, date
foobar()
date.today()
# TODO: Include good relative imports examples?
If a module can be executed as a script, it should include:
#!/usr/bin/env python3
# YOUR CODE HERE
if __name__ == "__main__":
# YOUR DRIVER CODE HERE (the sys.argv stuff is just an example)
import sys
print(sys.argv)
Basic Recipes
Starting Templates
Entrypoints:
#!/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()]
Leetcode
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).
Trie
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
TODO
- Maybe I can move
collections.defaultdict
to thedict
section, andcollections.Counter
to theset
section?
[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!)
General
- abs
- aiter
- all
- anext
- any
- ascii
- bin
- bool
- bytearray
- bytes
- callable
- @classmethod
- complex
- delattr
- dict
- dir
- divmod
- enumerate
- eval
- exec
- filter
- float
- format
- frozenset
- getattr
- globals
- hasattr
- hex
- id
- input
- int
- isinstance
- issubclass
- iter
- len
- list
- locals
- map
- max
- max
- memoryview
- min
- next
- object
- oct
- open
- ord
- pow
- property
- range
- repr
- reversed
- round
- set
- setattr
- sorted
- @staticmethod
- str
- sum
- super
- tuple
- type
- vars
- zip
- Infinite:
- Combinatoric:
- Misc. Finite: