Best Python Cheat Sheet
Best Python Cheat Sheet
Keyword
and del global nonlocal type 1
as elif if not while
assert else import or with
break except in pass yield
case 1 False is raise _1
class finally lambda return
continue for match 1 True
def from None try
1
Soft keywords
Decorator
A decorator is a callable that manipulates and returns a function.
def show_call(func):
"""
Print function name and arguments each time it is called.
"""
@wraps(func)
def out(*args, **kwds):
print(func.__name__, args, kwds)
return func(*args, **kwds)
return out
@show_call
def add(x, y):
return x + y
Scope
Scope levels:
Builtin Names pre-assigned in Enclosing Names defined in any
builtins module (closure) enclosing functions
Module (global) Names defined in current
module
Code in global scope
cannot access local
variables
>>> global_variable = 1
>>> def read_global():
... print(global_variable)
... local_variable = "only available in this function"
... print(local_variable)
>>> read_global()
1
>>> class C:
... class_variable = 1
... def __init__(self):
... self.instance_variable = 2
... def method(self):
... self.instance_variable = 3
... C.class_variable = 3
... method_variable = 1
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
Splat * operator
Function definition
Function call
Unpacking
if matching := pattern.search(data):
do_something(matching)
count = 0
while (count := count + 1) < 5:
print(count)
Flow control
while <condition>:
…
[else: # if loop completes without break
…]
if condition:
…
[elif condition:
…]*
[else:
…]
Match
3.10+
match <expression>:
case <pattern> [if <condition>]:
…
case <pattern1> | <pattern2>: # OR pattern
…
case _: # default case
…
Context manager
A with statement takes an object with special methods:
⯀ __enter__() - locks resources and optionally returns an object
⯀ __exit__() - releases resources, handles an exception raised in the block, optionally
suppressing it by returning True
class MyOpen:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
self.file = open(self.filename)
return self.file
def __exit__(self, exc_type, exception, traceback):
self.file.close()
Class
Instantiation
class C:
def __init__(self, a):
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):
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
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)
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[…] __detitem__(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)
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.
def IterableIterator:
def __iter__(self):
"""Make class iterable."""
return self
def __next__(self):
"""Implement to be iterable."""
if at_the_end:
raise StopIteration
return next_item
c = IterableIterator()
it = iter(c) # get iterator
next(it) # get next item
while value := next(it):
print(value)
Generator
def gen():
"""Generator function"""
for i in range(10):
yield i
g = gen()
String
Immutable sequence of characters.
<substring> in s True if string s.ljust(width, Left justify with
contains substring fillchar=' ') fillchar
s.startswith(<prefix True if string s.rjust(width, Right justify with
>[, start[, end]]) starts with prefix, fillchar=' ') fillchar
optionally search
s.center(width, Center with fillchar
bounded substring
fillchar=' ')
s.endswith(<suffix> True if string ends
s.rstrip(chars=None) Strip whitespace
[, start[, end]]) with suffix,
from right end, or
optionally search
passed characters
bounded substring
s.split(sep=None, Split on whitespace,
s.strip(chars=None) Strip whitespace
maxsplit=-1) or sep str at most
from both ends, or
maxsplit times
passed characters
s.splitlines(keepend Split lines on
s.lstrip(chars=None) Strip whitespace
s=False) [\n\r\f\v\x1c-
from left end, or
\x1e\x85\u2028\u2029
passed characters
] and \r\n
s.rstrip(chars=None) Strip whitespace
<separator>.join(<st Join strings with
from right end, or
rings>) separator
passed characters
s.find(<substring>) Index of first match
or -1
String formatting
f-string Output
f"{6/3}, {'a'+'b'}" '2, ab'
'{}, {}'.format(6/3, 'a'+'b')
f'{1:<5}' '1 '
f'{1:^5}' ' 1 '
f'{1:>5}' ' 1'
f'{1:.<5}' '1....'
f'{1:.>5}' '....1'
f'{1:0}' '1'
f'{1+1=}' '1+1=2' (= prepends)
f'{v!r}' repr(v)
f'{today:%d %b %Y}' '21 Jan 1984'
f'{1.729:.2f}' '1.73'
f'{1.7:04}' '01.7'
f'{1.7:4}' ' 1.7'
f"{'abc':.2}" 'ab'
f"{'abc':6.2}" 'ab '
f"{'abc'!r:6}" "'abc' "
f'{123456:,}' '123,456'
f'{123456:_}' '123_456'
f'{123456:+6}' ' +123'
f-string Output
f'{123456:=+6}' '+ 123'
f'{1.234:.2}' '1.2'
f'{1.234:.2f}' '1.23'
f'{1.234:.2e}' '1.230e+00'
f'{1.234:.2%}' '123.40%'
f'{164:b}' '10100100'
f'{164:o}' '244'
f'{164:X}' 'A4'
f'{164:c}' 'ÿ'
f'{1 #comment}' '1' (v3.12)
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-consumptive
*?, +?, Same as *, + and ?, as few as
(?<=…) Match preceding, positive
?? possible
lookbehind assertion
{m,n} m to n repetitions
(?<!…) Non-match preceding, negative
{m,n}? m to n repetitions, as few as lookbehind assertion
possible
(? Conditional match - A if group
[ ] Character set: e.g. '[a-zA-Z]' (group)A| previously matched else B
B)
[^ ] NOT character set
(? Set flags for RE ('i','L', 'm',
\ Escape chars '*?+&$|()',
letters) 's', 'u', 'x')
introduce special sequences
(?#…) Comment (ignored)
\\ Literal '\'
Regex flags
I or IGNORECASE <=> Case insensitive S or DOTALL <=> (?s) '.' matches ALL
(?i) matching chars, including
newline
L or LOCALE <=> (?L) \w, \W, \b, \B
depend on current U or UNICODE <=> (? \w, \W, \b, and \B
locale u) dependent on Unicode
database
M or MULTILINE <=> Match every new
(?m) line, not only X or VERBOSE <=> (? Ignores whitespace
start/end of string x) outside character
sets
Regex functions
compile(pattern[,fla Compiles Regular findall(pattern, Non-overlapping
gs=0]) Expression Object 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 objects
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])
Math / Number
int(<float|str|bool>) Integer
5
float(<int|str|bool>) Float (inexact, compare with
5.1, 1.2e-4 math.isclose(<float>, <float>)
complex(real=0, imag=0) Complex
3 - 2j, 2.1 + 0.8j
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)
Functions
pow(<num>, <num>) Power
<num> ** <num>
abs(<num>) Absolute
round(<num>[, ±ndigits]) Round
Mathematics
from math import (e, pi, inf, nan, isinf, isnan,
sin, cos, tan, asin, acos, atan, degrees, radians,
log, log10, log2)
Statistics
from statistics import mean, median, variance, stdev, quantiles, groupby
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
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]==x,
start[, stop]]) start/stop bounds search
x not in s True if no s[i]==x
reversed(s) Iterator on s in reverse
s1 + s2 Concatenate s1 and s2
order (for string use
s*n, n*s Concatenate n copies of s reversed(list(s)))
s.count(x) Count of s[i]==x sorted(s1, New sorted list
len(s) Number of items cmp=func,
key=getter,
min(s) Smallest item reverse=False)
max(s) Largest item
Indexing
Select items from sequence by index or slice.
>>> 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 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 steps
[3, 2, 1, 0]
>>> s[1:3]
[1, 2]
>>> s[1:5:2]
[1, 3]
Comparison
⯀ 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.
⯀ A sortable class should define __eq__(), __lt__(), __gt__(), __le__() and __ge__()
comparison special methods.
⯀ With functools @total_ordering decorator a class need only provide __eq__() and one
other comparison special method.
@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 = (1, 'a', 3.0) Create tuple
s = 1, 'a', 3.0
s = (1,) Single-item tuple
s = () Empty tuple
(1, 2, 3) == (1, 2) + (3,) Add makes new tuple
(1, 2, 1, 2) == (1, 2) * 2 Multply makes new tuple
Named tuple
Subclass with named items.
List
Mutable non-hashable sequence.
s = [1, 'a', Create list s.extend(it) Add elements from
3.0] s[len(s):len(s)] iterable to end
s = = it
list(range(3))
s.insert(i, x) Insert item at index i
s[i] = x Replace item index i with s[i:i] = [x]
x
s.remove(x) Remove item
s[<slice>] = it Replace slice with del
iterable s[s.index(x)]
del s[<slice>] Delete slice y = s.pop([i]) Remove and return last
s[<slice>] = [] item, or indexed item
s.append(x) Add element to end
s += x
s[len(s):len(s)]
= [x]
List comprehension
result = [expression for item1 in sequence1 {if condition1}
{for item2 in sequence2 {if condition2} … for itemN in sequenceN {if
conditionN}}]
# is equivalent to:
result = []
for item1 in sequence1:
for item2 in sequence2:
…
for itemN in sequenceN:
if condition1 and condition2 … and conditionN:
result.append(expression)
Dictionary
Mutable non-hashable key:value pair mapping.
dict() Empty dict d.pop(key) Remove and return
{} value for key, raise
KeyError if missing
dict(<sequence|mappi Create from
ng>) key:value pairs d.popitem() Remove and return
(key, value) pair
dict(**kwds) Create from keyword
(last-in, first-out)
arguments
d.clear() Remove all items
dict(zip(keys, Create from
values)) sequences of keys d.copy() Shallow copy
and values
collections.defaultd dict with default
dict.fromkeys(keys, Create from keys, ict(<type>) value <type>()
value=None) all set to value collections.defaultd e.g. dict with
ict(lambda: 42) default value 42
d.keys() Iterable of keys
d1.update(d2) Add/replace
d.values() Iterable of values
d1 |= d2 3.9+ key:value pairs from
d.items() Iterable of (key, d2 to d1
value) pairs
d3 = d1 | d2 Merge to new dict,
d.get(key, Get value for key, d3 = {**d1, **d2} d2 trumps d1
default=None) or default
{k for k, v in Set of keys with
d.setdefault(key, Get value for key, d.items() if given value
default=None) add if missing v==value}
Set
Mutable (set) and immutable (frozenset) sets.
set(iterable=None) New set from v in s Test membership
{1, 2, 3} iterable, or empty v not in s
frozenset(iterable=N But {} creates an
s1.issubset(s2) True if s1 is subset
one) empty dictionary
of s2
(sad!)
len(s) Cardinality
Bytes
Immutable sequence of bytes. Mutable version is bytearray.
b'<str>' Create from ASCII <bytes> = Return bytes even if only
characters and \x00-\xff <bytes>[<slice>] one element
bytes(<ints>) Create from int sequence list(<bytes>) Return ints in range 0 to
255
bytes(<str>, Create from string
'utf-8') <bytes_sep>.join Join byte_objs sequence
<str>.encode('ut (<byte_objs>) with bytes_sep separator
f-8')
str(<bytes>, Convert bytes to string
<int>.to_bytes(l Create from int 'utf-8')
ength, order, (order='big'|'little') <bytes>.decode('
signed=False) utf-8')
bytes.fromhex('< Create from hex pairs int.from_bytes(b Return int from bytes
hex>') (can be separated by ytes, order, (order='big'|'little')
whitespace) signed=False)
<int> = <bytes> Return int in range 0 to <bytes>.hex(sep= Return hex pairs
[<index>] 255 '',
bytes_per_sep=2)
def read_bytes(filename):
with open(filename, 'rb') as file:
return file.read()
Built-in functions
abs() Absolute value of number any() True if any element of
iterable is true (any([])
aiter() Asynchronous iterator for
== False)
an asynchronous iterable
ascii() A string with a printable
all() True if all elements of
representation of an
iterable are true
object
(all([]) == True)
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 '%'
Exception
try:
…
[except [Exception [as e]]:
…]
[except: # catch all
…]
[else: # if no exception
…]
[finally: # always executed
…]
try:
1 / 0
except ZeroDivisionError:
raise TypeError("Stop chain") from None
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 libraries
PYTHONWARNINGS Set warning level
PYTHONPATH Augment default search [default/error/always/mod
path for module files ule/once/ignore] (-W)
PYTHONSTARTUP Module to execute before PYTHONPROFILEIMP Show module import times
entering interactive ORTTIME (-X)
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