best-python-cheat-sheet
best-python-cheat-sheet
Keyword
and continue for match 1 True
as def from None try
assert del global nonlocal type 1
async elif if not while
await else import or with
break except in pass yield
case 1 False is raise _1
class finally lambda return
1
Soft keywords
Built-in
Built-in functions
abs(number) Absolute value of bytes(…) New bytes object
number from byte-integers,
string, or bytes
aiter(async_iterable Asynchronous
) iterator for an callable(object) True if object is
asynchronous callable
iterable
chr(i) One character string
all(iterable) True if all elements for unicode ordinal
of iterable are true i (0 <= i <=
(all([]) is True) 0x10ffff)
any(iterable) True if any element classmethod(func) Transform function
of iterable is true into class method
(any([]) is False)
compile(source, …) Compile source into
ascii(object) Return repr(object) code or AST object
with non-ASCII
complex(real=0, Complex number with
characters escaped
imag=0) the value real +
bin(number) Convert number to imag*1j
binary string
delattr(object, Delete the named
bool(object) Boolean value of name) attribute, if object
object, see __bool__ allows
breakpoint(*args, Drop into debugger dict(…) Create new
**kwds) by calling dictionary
sys.breakpointhook(*
dir([object]) List of names in the
args, **kwds)
local scope, or
bytearray(…) New array of bytes object.__dir__() or
from byte-integers, attributes
string, bytes, or
divmod(x, y) Return (quotient
object with buffer
x//y, remainder x%y)
API
© kieranholland.com 1 of 26
The *Best Python Cheat Sheet
2 of 26 © kieranholland.com
The *Best Python Cheat Sheet
Operator
Precedence (high->low) Description
(…,) […,] {…,} {…:…,} tuple, list, set, dict
s[i] s[i:j] s.attr f(…) index, slice, attribute, function call
await x await expression
+x, -x, ~x unary positive, negative, bitwise NOT
x ** y power
x * y, x @ y, x / y, x // y, x % y multiply, maxtrix multiply, divide, floor
divide, modulus
x + y, x - y add, substract
x << y x >> y bitwise shift left, right
x & y bitwise and
x ^ y bitwise exclusive or
x | y bitwise or
x<y x<=y x>y x>=y x==y x!=y comparison,
x is y x is not y identity,
x in s x not in s membership
not x boolean negation
x and y boolean and
x or y boolean or
… if … else … conditional expression
lambda lambda expression
:= assignment expression
© kieranholland.com 3 of 26
The *Best Python Cheat Sheet
count = 0
while (count := count + 1) < 5:
print(count)
>>> z = [1, 2, 3, 4, 5]
>>> [x for i in z if (x:=i**2) > 10]
[16, 25]
Assignment unpacking
Unpack multiple values to a name using the splat operator.
Flow control
while <condition>:
…
[else: # only if loop completes without break
…]
4 of 26 © kieranholland.com
The *Best Python Cheat Sheet
if <condition>:
…
[elif <condition>:
…]*
[else:
…]
Context manager
A with statement takes an object with special methods:
◼ __enter__() - locks resources and optionally returns an object
◼ __exit__() - releases resources, handles any exception raised in the block,
optionally suppressing it by returning True
class AutoClose:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
self.f = open(self.filename)
return self.f
def __exit__(self, exc_type, exception, traceback):
self.f.close()
Match
3.10+
match <expression>:
case <pattern>[ if <condition>]: # conditional match, if "guard" clause
…
case <pattern1> | <pattern2>: # OR pattern
…
case _: # default case
…
© kieranholland.com 5 of 26
The *Best Python Cheat Sheet
◼ Class patterns
◼ Do not create a new instance of the class
◼ Accept positional parameters if class defines __match_args__ special attribute
(e.g. dataclass)
◼ Sequence patterns support assignment unpacking
◼ Names bound in a match statement are visible after the match statement
Scope
Scope levels:
Builtin Names pre-assigned in Generator Names contained within
builtins module expression generator expression
Module (global) Names defined in current Comprehension Names contained within
module comprehension
Note: Code in global
Class Names shared across all
scope cannot access
instances
local variables
Instance Names contained within a
Enclosing Names defined in any
specific instance
(closure) enclosing functions
Method Names contained within a
Function Names defined in current
specific instance method
(local) function
Note: By default, has
read-only access to
module and enclosing
function names
By default, assignment
creates a new local name
global <name> grants
read/write access to
specified module name
nonlocal <name> grants
read/write access to
specified name in
closest enclosing
function defining that
name
6 of 26 © kieranholland.com
The *Best Python Cheat Sheet
>>> global_name = 1
>>> def read_global():
... print(global_name)
... local_name = "only available in this function"
>>> read_global()
1
>>> def write_global():
... global global_name # enable write to global
... global_name = 2
>>> write_global()
>>> print(global_name)
2
>>> def write_nonlocal():
... closure_name = 1
... def nested():
... nonlocal closure_name # enable write to nonlocal
... closure_name = 2
... nested()
... print(closure_name)
>>> write_nonlocal()
2
class C:
class_name = 1 # shared by all instances
def __init__(self):
self.instance_name = 2 # only on this instance
def method(self):
self.instance_name = 3 # update instance name
C.class_name = 3 # update class name
method_name = 1 # set method local name
Sequence
Operations on sequence types (Bytes, List, Tuple, String).
x in s True if any s[i] == x s.index(x[, Smallest i where s[i] ==
start[, stop]]) x, start/stop bounds
x not in s True if no s[i] == x
search
s1 + s2 Concatenate s1 and s2
reversed(s) Iterator on s in reverse
s * n, n * s Concatenate n copies of order
s For string use
s.count(x) Count of s[i] == x reversed(list(s))
Indexing
Select items from sequence by index or slice.
© kieranholland.com 7 of 26
The *Best Python Cheat Sheet
>>> s = [0, 1, 2, 3, 4]
>>> s[0] # 0-based indexing
0
>>> s[-1] # negative indexing from end
4
>>> s[slice(2)] # slice(stop) - index from 0 until stop (exclusive)
[0, 1]
>>> s[slice(1, 5, 3)] # slice(start, stop[, step]) - index from start to stop
(exclusive), with optional step size (+|-)
[1, 4]
>>> s[:2] # slices are created implicitly when indexing with ':'
[start:stop:step]
[0, 1]
>>> s[3::-1] # negative step
[3, 2, 1, 0]
>>> s[1:3]
[1, 2]
>>> s[1:5:2]
[1, 3]
Comparison
◼ A sortable class should define __eq__(), __lt__(), __gt__(), __le__() and __ge__()
special methods.
◼ With functools @total_ordering decorator a class need only provide __eq__() and
one other comparison special method.
◼ Sequence comparison: values are compared in order until a pair of unequal values
is found. The comparison of these two values is then returned. If all values are
equal, the shorter sequence is lesser.
@total_ordering
class C:
def __init__(self, a):
self.a = a
def __eq__(self, other):
if isinstance(other, type(self)):
return self.a == other.a
return NotImplemented
def __lt__(self, other):
if isinstance(other, type(self)):
return self.a < other.a
return NotImplemented
Tuple
Immutable hashable sequence.
s = () Empty tuple
s = (1, 'a', 3.0) Create from items
s = 1, 'a', 3.0
s = (1,) Single-item tuple
(1, 2, 3) == (1, 2) + (3,) Add makes new tuple
(1, 2, 1, 2) == (1, 2) * 2 Multiply makes new tuple
Named tuple
Tuple subclass with named items. Also: typing.NamedTuple
8 of 26 © kieranholland.com
The *Best Python Cheat Sheet
List
Mutable non-hashable sequence.
s = [] Empty list s.extend(it) Add items from iterable
s[len(s):len(s) to end
s = [1, 'a', Create from items
] = it
3.0]
s = s.insert(i, x) Insert item at index i
list(range(3)) s[i:i] = [x]
s[i] = x Replace item index i s.remove(x) Remove first item where
with x del s[i] == x
s[s.index(x)]
s[<slice>] = it Replace slice with
iterable y = s.pop([i]) Remove and return last
item or indexed item
del s[<slice>] Remove slice
s[<slice>] = [] s.reverse() Reverse items in place
s.append(x) Add item to end s.sort(cmp=func Sort items in place,
s += x , key=getter, default ascending
s[len(s):len(s) reverse=False)
] = [x]
List comprehension
# is equivalent to:
result = []
for item1 in <iterable1>:
for item2 in <iterable2>:
…
for itemN in <iterableN>:
if <condition1> and <condition2> … and <conditionN>:
result.append(<expression>)
Dictionary
Mutable non-hashable key:value pair mapping.
dict() Empty dict dict.fromkeys(keys, Create from keys,
{} value=None) all set to value
dict(<sequence|mappi Create from d.keys() Iterable of keys
ng>) key:value pairs
d.values() Iterable of values
{'d':4, 'a':2}
d.items() Iterable of (key,
dict(**kwds) Create from keyword
value) pairs
arguments
d.get(key, Get value for key,
dict(zip(keys, Create from
default=None) or default
values)) sequences of keys
and values
© kieranholland.com 9 of 26
The *Best Python Cheat Sheet
Dict comprehension
Set
Mutable (set) and immutable (frozenset) sets.
set() Empty set s.clear() [mutable] Remove all elements
frozenset()
s1.intersection(s2[, New set of shared
{1, 2, 3} Create from items, s3…]) elements
note: {} creates s1 & s2
empty dict - sad!
s1.intersection_upda Update s1 to
set(iterable) Create from iterable te(s2) [mutable] intersection with s2
{*iterable}
s1.union(s2[, s3…]) New set of all
len(s) Cardinality s1 | s2 elements
v in s Test membership s1.difference(s2[, New set of elements
v not in s s3…]) unique to s1
s1 - s2
s1.issubset(s2) True if s1 is subset
of s2 s1.difference_update Remove s1 elements
(s2) [mutable] intersecting with s2
s1.issuperset(s2) True if s1 is
superset of s2 s1.symmetric_differe New set of unshared
nce(s2) elements
s.add(v) [mutable] Add element
s1 ^ s2
s.remove(v) Remove element
s1.symmetric_differe Update s1 to
[mutable] (KeyError if not
nce_update(s2) symmetric difference
found)
[mutable] with s2
s.discard(v) Remove element if
s.copy() Shallow copy
[mutable] present
s.update(it1[, Add elements from
s.pop() [mutable] Remove and return
it2…]) [mutable] iterables
arbitrary element
(KeyError if empty)
Set comprehension
Bytes
Immutable sequence of bytes. Mutable version is bytearray.
10 of 26 © kieranholland.com
The *Best Python Cheat Sheet
def read_bytes(filename):
with open(filename, 'rb') as f:
return f.read()
Function
Function definition
# var-positional
def f(*args): … # f(1, 2)
def f(x, *args): … # f(1, 2)
def f(*args, z): … # f(1, z=2)
# var-keyword
def f(**kwds): … # f(x=1, y=2)
def f(x, **kwds): … # f(x=1, y=2) | f(1, y=2)
# positional-only before /
def f(x, /, y): … # f(1, 2) | f(1, y=2)
def f(x, y, /): … # f(1, 2)
# keyword-only after *
def f(x, *, y): … # f(x=1, y=2) | f(1, y=2)
def f(*, x, y): … # f(x=1, y=2)
Function call
© kieranholland.com 11 of 26
The *Best Python Cheat Sheet
Class
Instantiation
class C:
"""Class docstring."""
def __init__(self, a):
"""Method docstring."""
self.a = a
def __repr__(self):
"""Used for repr(c), also for str(c) if __str__ not defined."""
return f'{self.__class__.__name__}({self.a!r})'
def __str__(self):
"""Used for str(c), e.g. print(c)"""
return str(self.a)
@classmethod
def get_class_name(cls): # passed class rather than instance
return cls.__name__
@staticmethod
def static(): # passed nothing
return 1
Instance property
class C:
@property
def f(self):
if not hasattr(self, '_f'):
return
return self._f
@f.setter
def f(self, value):
self._f = value
12 of 26 © kieranholland.com
The *Best Python Cheat Sheet
© kieranholland.com 13 of 26
The *Best Python Cheat Sheet
Operator Method
-self __neg__(self)
+self __pos__(self)
abs(self) __abs__(self)
~self __invert__(self) [bitwise]
self == other __eq__(self) [default 'is', requires __hash__]
self != other __ne__(self)
self < other __lt__(self, other)
self <= other __le__(self, other)
self > other __gt__(self, other)
self >= other __ge__(self, other)
item in self __contains__(self, item)
bool(self) __bool__(self)
if self:
if not self:
bytes(self) __bytes__(self)
complex(self) __complex__(self)
float(self) __float__(self)
int(self) __int__(self)
round(self) __round__(self[, ndigits])
math.ceil(self) __ceil__(self)
math.floor(self) __floor__(self)
math.trunc(self) __trunc__(self)
dir(self) __dir__(self)
format(self) __format__(self, format_spec)
hash(self) __hash__(self)
iter(self) __iter__(self)
len(self) __len__(self)
repr(self) __repr__(self)
reversed(self) __reversed__(self)
str(self) __str__(self)
self(*args, **kwds) __call__(self, *args, **kwds)
self[…] __getitem__(self, key)
self[…] = 1 __setitem__(self, key, value)
del self[…] __delitem__(self, key)
other[self] __index__(self)
self.name __getattribute__(self, name)
__getattr__(self, name) [if AttributeError]
self.name = 1 __setattr__(self, name, value)
del self.name __delattr__(self, name)
with self: __enter__(self)
__exit__(self, exc_type, exc_value, traceback)
await self __await__(self)
Decorator
Decorator syntax passes a function or class to a callable and replaces it with the
return value.
14 of 26 © kieranholland.com
The *Best Python Cheat Sheet
def show_call(obj):
"""
Decorator that prints obj name and arguments each time obj is called.
"""
def show_call_wrapper(*args, **kwds):
print(obj.__name__, args, kwds)
return obj(*args, **kwds)
return show_call_wrapper
# is equivalent to
add = show_call(add)
# is equivalent to
C = show_call(C)
>>> C(a=42)
C () {'a': 42}
© kieranholland.com 15 of 26
The *Best Python Cheat Sheet
@show_call_if(False)
def add(x, y):
return x + y
# is equivalent to
add = show_call_if(False)(add)
@show_call_if(True)
def add(x, y):
return x + y
>>> add.__name__
'show_call_wrapper' # ugh! decorated function has different metadata
def show_call_preserve_meta(obj):
@wraps(obj)
def show_call_wrapper(*args, **kwds):
print(obj.__name__, args, kwds)
return obj(*args, **kwds)
return show_call_wrapper
@show_call_preserve_meta
def add(x, y):
return x + y
>>> add.__name__
'add'
Iterator
An iterator implements the __iter__() method, returning an iterable that implements
the __next__() method. The __next__() method returns the next item in the collection
and raises StopIteration when done.
16 of 26 © kieranholland.com
The *Best Python Cheat Sheet
class C:
def __init__(self, items):
self.items = items
def __iter__(self):
"""Make class its own iterable."""
return self
def __next__(self):
"""Implement to be iterable."""
if self.items:
return self.items.pop()
raise StopIteration
Generator
A function with a yield statement returns a generator iterator and suspends function
processing. Each iteration over the generator iterator resumes function execution,
returns the next yield value, and suspends again.
def gen():
"""Generator function"""
for i in [13, 29]:
yield i
>>> g = gen()
>>> next(g) # next value
13
>>> for item in gen(): # iterate over values
... print(item)
13
29
>>> list(gen()) # list all values
[13, 29]
def parent_gen():
yield from gen() # delegate yield to another generator
>>> list(parent_gen())
[13, 29]
Generator expression
String
Immutable sequence of characters.
© kieranholland.com 17 of 26
The *Best Python Cheat Sheet
18 of 26 © kieranholland.com
The *Best Python Cheat Sheet
String escape
Sequence Escape
Literal backslash \\
Single quote \'
Double quote \"
Backspace \b
Carriage return \r
Newline \n
Tab \t
Vertical tab \v
Null \0
Hex value \xff
Octal value \o77
Unicode 16 bit \uxxxx
Unicode 32 bit \Uxxxxxxxx
Unicode name \N{name}
String formatting
Format f-string Output
Escape curly braces f"{{}}" '{}'
Expression f"{6/3}, {'a'+'b'}" '2, ab'
'{}, {}'.format(6/3,
'a'+'b')
Justify left f'{1:<5}' '1 '
Justify center f'{1:^5}' ' 1 '
Justify right f'{1:>5}' ' 1'
Justify left with char f'{1:.<5}' '1....'
Justify right with char f'{1:.>5}' '....1'
Trim f"{'abc':.2}" 'ab'
Trim justify left f"{'abc':6.2}" 'ab '
ascii() f'{v!a}' ascii(v)
repr() f'{v!r}' repr(v)
str() f'{v!s}' str(v)
Justify left repr() f"{'abc'!r:6}" "'abc' "
Date format f'{today:%d %b %Y}' '21 Jan 1984'
© kieranholland.com 19 of 26
The *Best Python Cheat Sheet
Regex
Standard library re module provides Python regular expressions.
>>> import re
>>> my_re = re.compile(r'name is (?P<name>[A-Za-z]+)')
>>> match = my_re.search('My name is Douglas.')
>>> match.group()
'name is Douglas'
>>> match.group(1)
'Douglas'
>>> match.groupdict()['name']
'Douglas'
Regex syntax
. Any character (newline if | Or
DOTALL)
(…) Group
^ Start of string (every line if
(?:…) Non-capturing group
MULTILINE)
(? Named group
$ End of string (every line if
P<name>…)
MULTILINE)
(?P=name) Match text matched by earlier
* 0 or more of preceding
group
+ 1 or more of preceding
(?=…) Match next, non-consumptive
? 0 or 1 of preceding
(?!…) Non-match next, non-
*?, +?, Same as *, + and ?, as few as consumptive
?? possible
(?<=…) Match preceding, positive
{m,n} m to n repetitions lookbehind assertion
{m,n}? m to n repetitions, as few as (?<!…) Non-match preceding, negative
possible lookbehind assertion
[…] Character set: e.g. '[a-zA-Z]' (? Conditional match - A if group
(group)A| previously matched else B
[^…] NOT character set
B)
\ Escape chars '*?+&$|()',
(? Set flags for RE ('i','L',
introduce special sequences
letters) 'm', 's', 'u', 'x')
\\ Literal '\'
(?#…) Comment (ignored)
20 of 26 © kieranholland.com
The *Best Python Cheat Sheet
Regex flags
Flags modify regex behaviour. Pass to regex functions (e.g. re.A | re.ASCII) or embed
in regular expression (e.g. (?a)).
(?a) | A | ASCII ASCII-only match for (?m) | M | MULTILINE Match every new
\w, \W, \b, \B, \d, line, not only
\D, \s, \S (default start/end of string
is Unicode)
(?s) | S | DOTALL '.' matches ALL
(?i) | I | Case insensitive chars, including
IGNORECASE matching newline
(?L) | L | LOCALE Apply current locale (?x) | X | VERBOSE Ignores whitespace
for \w, \W, \b, \B outside character
(discouraged) sets
DEBUG Display expression
debug info
Regex functions
compile(pattern[, Compiles findall(pattern, Non-overlapping
flags=0]) Regular Expression Ob string) matches as list of
groups or tuples
escape(string) Escape non-
(>1)
alphanumerics
finditer(pattern, Iterator over non-
match(pattern, Match from start
string[, flags]) overlapping matches
string[, flags])
sub(pattern, repl, Replace count first
search(pattern, Match anywhere
string[, count=0]) leftmost non-
string[, flags])
overlapping; If repl
split(pattern, Splits by pattern, is function, called
string[, keeping splitter if with a MatchObj
maxsplit=0]) grouped
subn(pattern, repl, Like sub(), but
string[, count=0]) returns (newString,
numberOfSubsMade)
Regex object
flags Flags split(string[, See split() function
maxsplit=0])
groupindex {group name: group
number} findall(string[, See findall()
pos[, endpos]]) function
pattern Pattern
finditer(string[, See finditer()
match(string[, pos] Match from start of
pos[, endpos]]) function
[, endpos]) target[pos:endpos]
sub(repl, string[, See sub() function
search(string[, pos] Match anywhere in
count=0])
[, endpos]) target[pos:endpos]
subn(repl, string[, See subn() function
count=0])
© kieranholland.com 21 of 26
The *Best Python Cheat Sheet
Number
bool([object]) Boolean, see __bool__
True, False special method
int([float|str|bool]) Integer, see __int__
5 special method
float([int|str|bool]) Float (inexact, compare with
5.1, 1.2e-4 math.isclose(<float>, <float>)
See __float__ special method
complex(real=0, imag=0) Complex, see __complex__
3 - 2j, 2.1 + 0.8j special method
fractions.Fraction(<numerator>, <denominator>) Fraction
decimal.Decimal([str|int]) Decimal (exact, set precision:
decimal.getcontext().prec =
<int>)
bin([int]) Binary
0b101010
int('101010', 2)
int('0b101010', 0)
hex([int]) Hex
0x2a
int('2a', 16)
int('0x2a', 0)
Mathematics
22 of 26 © kieranholland.com
The *Best Python Cheat Sheet
Random
>>> from random import random, randint, choice, shuffle, gauss, triangular, seed
>>> random() # float inside [0, 1)
0.42
>>> randint(1, 100) # int inside [<from>, <to>]
42
>>> choice(range(100)) # random item from sequence
42
Time
The datetime module provides immutable hashable date, time, datetime, and
timedelta classes.
Time formatting
Code Output
%a Day name short (Mon)
%A Day name full (Monday)
%b Month name short (Jan)
%B Month name full (January)
%c Locale datetime format
%d Day of month [01,31]
%f Microsecond [000000,999999]
%H Hour (24-hour) [00,23]
%I Hour (12-hour) [01,12]
%j Day of year [001,366]
%m Month [01,12]
%M Minute [00,59]
%p Locale format for AM/PM
%S Second [00,61]. Yes, 61!
%U Week number (Sunday start) [00(partial),53]
%w Day number [0(Sunday),6]
%W Week number (Monday start) [00(partial),53]
%x Locale date format
%X Locale time format
%y Year without century [00,99]
%Y Year with century (2023)
%Z Time zone ('' if no TZ)
%z UTC offset (+HHMM/-HHMM, '' if no TZ)
%% Literal '%'
© kieranholland.com 23 of 26
The *Best Python Cheat Sheet
Exception
try:
…
[except [<Exception>[ as e]]:
…]
[except: # catch all
…]
[else: # if no exception
…]
[finally: # always executed
…]
try:
1 / 0
except ZeroDivisionError:
# from None hides exception context
raise TypeError("Hide ZeroDivisionError") from None
24 of 26 © kieranholland.com
The *Best Python Cheat Sheet
© kieranholland.com 25 of 26
The *Best Python Cheat Sheet
Execution
# Hide warnings
PYTHONWARNINGS="ignore"
# OR
$ python -W ignore foo.py
# OR
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
Environment variables
PYTHONHOME Change location of PYTHONOPTIMIZE Optimise execution (-O)
standard Python
PYTHONWARNINGS Set warning level
libraries
[default/error/always/mo
PYTHONPATH Augment default search dule/once/ignore] (-W)
path for module files
PYTHONPROFILEIM Show module import times
PYTHONSTARTUP Module to execute before PORTTIME (-X)
entering interactive
prompt
sitecustomize.py / usercustomize.py
Before __main__ module is executed Python automatically imports:
◼ sitecustomize.py in the system site-packages directory
◼ usercustomize.py in the user site-packages directory
26 of 26 © kieranholland.com