0% found this document useful (0 votes)
37 views23 pages

Best Python Cheat Sheet

The document is a comprehensive Python cheat sheet covering various aspects of the language including built-in functions, flow control, operators, classes, and more. It provides detailed explanations and examples for decorators, scope, generators, and context managers, among other topics. The cheat sheet is designed for users familiar with Python 3.8+ and serves as a quick reference guide for essential programming concepts.

Uploaded by

Kasi Majji
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views23 pages

Best Python Cheat Sheet

The document is a comprehensive Python cheat sheet covering various aspects of the language including built-in functions, flow control, operators, classes, and more. It provides detailed explanations and examples for decorators, scope, generators, and context managers, among other topics. The cheat sheet is designed for users familiar with Python 3.8+ and serves as a quick reference guide for essential programming concepts.

Uploaded by

Kasi Majji
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

The Best* Python Cheat Sheet

Just what you need


Built-in functions (18) Execution (23) Math / Number (14) String (10)
Bytes (18) Flow control (5) Operator (3) Testing (23)
Class (6) Generator (10) Regex (12) Time (20)
Debugging (23) Iterator (9) Resources (23) Tuple (16)
Decorator (1) Keyword (1) Scope (1)
Dictionary (17) Library (23) Sequence (15)
Exception (21) List (16) Set (17)

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.

# wraps decorator copies metadata of decorated function (func) to wrapped function


(out)
from functools import wraps

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

1 Apr 2024 | Python 3.8+ © kieranholland.com 1 of 23


The Best* Python Cheat Sheet

Function (local) Names defined in current Comprehension Names contained within


function comprehension
By default, has read-only
Class Names shared across all
access to module and
instances
enclosing function names
By default, assignment Instance Names contained within a
creates a new local name specific instance
global <name> grants Method Names contained within a
read/write access to specific instance method
specified module name
nonlocal <name> grants
read/write access to
specified name in closest
enclosing function
defining that name
Generator Names contained within
expression generator expression

⯀ globals() - return dict of module scope variables


⯀ locals() - return dict of local scope variables

>>> global_variable = 1
>>> def read_global():
... print(global_variable)
... local_variable = "only available in this function"
... print(local_variable)
>>> read_global()
1

>>> def write_global():


... global global_variable
... global_variable = 2
>>> write_global()
>>> print(global_variable)
2

>>> def write_nonlocal():


... x = 1
... def nested():
... nonlocal x
... x = 2
... nested()
... print(x)
>>> write_nonlocal()
2

>>> 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

2 of 23 © kieranholland.com Python 3.8+ | 1 Apr 2024


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

Assignment Usually equivalent


a = b Assign object b to label a
a += b a = a + b
a -= b a = a - b
a *= b a = a * b
a /= b a = a / b (true division)
a //= b a = a // b (floor division)
a %= b a = a % b
a **= b a = a ** b
a &= b a = a & b
a |= b a = a | b
a ^= b a = a ^ b
a >>= b a = a >> b
a <<= b a = a << b

1 Apr 2024 | Python 3.8+ © kieranholland.com 3 of 23


The Best* Python Cheat Sheet

Splat * operator
Function definition

def f(*args): … # f(1, 2, 3)


def f(x, *args): … # f(1, 2, 3)
def f(*args, z): … # f(1, 2, z=3)

def f(**kwds): … # f(x=1, y=2, z=3)


def f(x, **kwds): … # f(x=1, y=2, z=3) | f(1, y=2, z=3)
def f(*args, **kwds): … # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1,
2, 3)
def f(x, *args, **kwds): … # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1,
2, 3)
def f(*args, y, **kwds): … # f(x=1, y=2, z=3) | f(1, y=2, z=3)

def f(*, x, y, z): … # f(x=1, y=2, z=3)


def f(x, *, y, z): … # f(x=1, y=2, z=3) | f(1, y=2, z=3)
def f(x, y, *, z): … # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3)

Function call

args = (1, 2) # * expands sequence to positional arguments


kwds = {'x': 3, 'y': 4} # ** expands dictionary to keyword arguments
func(*args, **kwds) # is the same as:
func(1, 2, x=3, y=4)

Unpacking

head, *body = s # unpack assignment


head, *body, tail = s
*body, tail = s
s = [*it[, …]] # unpack to list
s = (*it[, …]) # unpack to tuple
s = {*it[, …]} # unpack to set
d2 = {**d1[, …]} # unpack to dict

Walrus operator (Assignment expression)


Assign a value and return that value.

if matching := pattern.search(data):
do_something(matching)

count = 0
while (count := count + 1) < 5:
print(count)

4 of 23 © kieranholland.com Python 3.8+ | 1 Apr 2024


The Best* Python Cheat Sheet

Flow control

for item in <iterable>:



[else: # if loop completes without break
…]

while <condition>:

[else: # if loop completes without break
…]

break # immediately exit loop


continue # skip to next loop iteration
return [value] # exit function, return value | None
yield [value] # exit generator, yield value | None
assert <expr>[, message] # if not expr raise AssertionError(message)

if condition:

[elif condition:
…]*
[else:
…]

<expression1> if <condition> else <expression2>

with <expression> [as name]:


Match
3.10+

match <expression>:
case <pattern> [if <condition>]:

case <pattern1> | <pattern2>: # OR pattern

case _: # default case

Match case pattern


1/'abc'/True/None/math.pi Value pattern, match literal or dotted name
<type>() Class pattern, match any object of that
type
<type>(<name>=<pattern>, …) Class pattern, match object with matching
attributes
<name> Capture pattern, match any object, bind to
name
_ Wildcard, match any object
<pattern> | <pattern> [| …] Or pattern, match any of the patterns
<pattern> as <name> As pattern, bind match to name

1 Apr 2024 | Python 3.8+ © kieranholland.com 5 of 23


The Best* Python Cheat Sheet

[<pattern>[, …[, *args]] Sequence pattern (list|tuple) matches


sequence with matching items
{<value_pattern>: <pattern>[, …[, **kwds]]} Mapping pattern matches any dictionary with
matching items

⯀ Class patterns do not create a new instance of the class


⯀ Patterns can be bracketed to override precedence [| > as > ,]
⯀ Built-in types allow a single positional pattern that is matched against the entire
object.
⯀ Names bound in the matching case + names bound in its block are visible after the
match statement

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()

>>> with open('test.txt', 'w') as file: …


... file.write('Hello World!')
>>> with MyOpen('test.txt') as file: …
... print(file.read())
Hello World!

Class

6 of 23 © kieranholland.com Python 3.8+ | 1 Apr 2024


The Best* Python Cheat Sheet

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

# class instantiation does this


obj = cls.__new__(cls, *args, **kwds)
if isinstance(obj, cls):
obj.__init__(*args, **kwds)

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

1 Apr 2024 | Python 3.8+ © kieranholland.com 7 of 23


The Best* Python Cheat Sheet

Class special methods


Operator Method
self + other __add__(self, other)
other + self __radd__(self, other)
self += other __iadd__(self, other)
self - other __sub__(self, other)
other - self __rsub__(self, other)
self -= other __isub__(self, other)
self * other __mul__(self, other)
other * self __rmul__(self, other)
self *= other __imul__(self, other)
self @ other __matmul__(self, other)
other @ self __rmatmul__(self, other)
self @= other __imatmul__(self, other)
self / other __truediv__(self, other)
other / self __rtruediv__(self, other)
self /= other __itruediv__(self, other)
self // other __floordiv__(self, other)
other // self __rfloordiv__(self, other)
self //= other __ifloordiv__(self, other)
self % other __mod__(self, other)
other % self __rmod__(self, other)
self %= other __imod__(self, other)
self ** other __pow__(self, other)
other ** self __rpow__(self, other)
self **= other __ipow__(self, other)
self << other __lshift__(self, other)
other << self __rlshift__(self, other)
self <<= other __ilshift__(self, other)
self >> other __rshift__(self, other)
other >> self __rrshift__(self, other)
self >>= other __irshift__(self, other)
self & other __and__(self, other)
other & self __rand__(self, other)
self &= other __iand__(self, other)
self | other __or__(self, other)
other | self __ror__(self, other)
self |= other __ior__(self, other)
self ^ other __xor__(self, other)
other ^ self __rxor__(self, other)
self ^= other __ixor__(self, other)
divmod(self, other) __divmod__(self, other)
divmod(self, other) __rdivmod__(self, other)

8 of 23 © kieranholland.com Python 3.8+ | 1 Apr 2024


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)
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.

1 Apr 2024 | Python 3.8+ © kieranholland.com 9 of 23


The Best* Python Cheat Sheet

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

g = (expression for item in iterable if condition) # generator expression

def gen():
"""Generator function"""
for i in range(10):
yield i
g = gen()

next(g) # next item


list(g) # list all items
yield from g # delegate yield to another generator

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

10 of 23 © kieranholland.com Python 3.8+ | 1 Apr 2024


The Best* Python Cheat Sheet

s.index(<substring>) Index of first match s.isdecimal() True if [0-9], [०-९]


or raise ValueError or [٩-٠]
s.lower() To lower case s.isdigit() True if isdecimal()
or [²³¹…]
s.upper() To upper case
s.isnumeric() True if isdigit() or
s.title() To title case (The
Quick Brown Fox)
零〇一
[¼½¾ …]
s.isalnum() True if isnumeric()
s.capitalize() Capitalize first
or [a-zA-Z…]
letter
s.isprintable() True if isalnum() or
s.replace(old, new[, Replace old with new
[ !
count]) at most count times
s.isspace() True if [
s.translate(<table>) Use
\t\n\r\f\v\x1c-
str.maketrans(<dict>)
\x1f\x85\xa0…]
to generate table
head, sep, tail = Search for separator
chr(<int>) Integer to Unicode
s.partition(<separat from start and split
character
or>)
ord(<str>) Unicode character to
head, sep, tail = Search for separator
integer
s.rpartition(<separa from end and split
tor>)

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'

1 Apr 2024 | Python 3.8+ © kieranholland.com 11 of 23


The Best* Python Cheat Sheet

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 '\'

12 of 23 © kieranholland.com Python 3.8+ | 1 Apr 2024


The Best* Python Cheat Sheet

Regex special sequences


\<n> Match by integer group \s Whitespace [ \t\n\r\f\v]
reference starting from 1
\S Non-whitespace
\A Start of string
\w Alphanumeric (depends on LOCALE
\b Word boundary flag)
\B Not word boundary \W Non-alphanumeric
\d Decimal digit \Z End of string
\D Non-decimal digit

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])

Regex match objects


pos pos passed to search or match re RE object
endpos endpos passed to search or
match

1 Apr 2024 | Python 3.8+ © kieranholland.com 13 of 23


The Best* Python Cheat Sheet

group([g1, One or more groups of match span(group) (start(group), end(group));


g2, ...]) One arg, result is a string (None, None) if group didn't
Multiple args, result is contibute
tuple
string String passed to match() or
If gi is 0, returns the
search()
entire matching string
If 1 <= gi <= 99, returns
string matching group
(None if no such group)
May also be a group name
Tuple of match groups
Non-participating groups are
None
String if len(tuple)==1
start(group) Indices of start & end of
, end(group) group match (None if group
exists but didn't contribute)

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

14 of 23 © kieranholland.com Python 3.8+ | 1 Apr 2024


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

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.

1 Apr 2024 | Python 3.8+ © kieranholland.com 15 of 23


The Best* Python Cheat Sheet

from functools import total_ordering

@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.

>>> from collections import namedtuple


>>> Point = namedtuple('Point', ('x', 'y')) # or namedtuple('Point', 'x y')
>>> p = Point(1, y=2)
Point(x=1, y=2)
>>> p[0]
1
>>> p.y
2

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]

16 of 23 © kieranholland.com Python 3.8+ | 1 Apr 2024


The Best* Python Cheat Sheet

s.reverse() Reverse in place


s.sort(cmp=func, Sort in place, default
key=getter, ascending
reverse=False)

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

1 Apr 2024 | Python 3.8+ © kieranholland.com 17 of 23


The Best* Python Cheat Sheet

s1.issuperset(s2) True if s1 is s1.intersection(s2[, New set of shared


superset of s2 s3…]) elements
s1 & s2
s.add(v) Add element
s1.union(s2[, s3…]) New set of all
s.remove(v) Remove element
s1 | s2 elements
(KeyError if not
found) s1.difference(s2[, New set of elements
s3…]) unique to s1
s.discard(v) Remove element if
s1 - s2
present
s1.symmetric_differe New set of unshared
s.pop() Remove and return
nce(s2) elements
arbitrary element
s1 ^ s2
(KeyError if empty)
s.copy() Shallow copy
s.clear() Remove all elements
s.update(it1[, Add all values from
it2…]) iterables

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()

def write_bytes(filename, bytes_obj):


with open(filename, 'wb') as file:
file.write(bytes_obj)

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)

18 of 23 © kieranholland.com Python 3.8+ | 1 Apr 2024


The Best* Python Cheat Sheet

bin() Convert integer number to id() Return unique integer


binary string identifier of object
bool() Boolean value __import__() Invoked by the import
statement
breakpoint() Drop into debugger at
call site input(prompt='') Read string from stdin,
with optional prompt
bytearray() New array of bytes
int() Create integer from
bytes() New bytes object
number or string
callable() True if the argument is
isinstance() True if object is
callable
instance of given class
chr() One character string for
issubclass() True if class is subclass
unicode ordinal i (0 <= i
of given class
<= 0x10ffff)
iter() Iterator for object
classmethod() Transform method into
class method len() Length of object
compile() Compile source into code list() Create list
or AST object
locals() Dictionary of current
complex() Complex number with the local symbol table
value real + imag*1j
map() Apply function to every
delattr() Delete the named item of iterable
attribute, if object
max() Largest item in an
allows
iterable
dict() Create new dictionary
memoryview() Access internal object
dir() List of names in the data via buffer protocol
local scope
min() Smallest item in an
divmod() Pair of numbers iterable
(quotient, remainder)
next() Next item from iterator
enumerate() Enumerate object as (n,
object() New featureless object
item) pairs
oct() Convert integer to octal
eval() Execute expression
string
exec() Execute Python code
open() Open file object
filter() Make iterator from an
ord() Integer representing
iterable, return True
Unicode code point of
float() Floating point number character
from number or string
pow() Return base to the power
format() Formatted representation exp.
frozenset() New frozenset object print() Print object to text
stream file
getattr() Get value of named
attribute of object property() Property decorator
globals() Dictionary of current range() Generate integer sequence
module namespace
repr() String representation of
hasattr() True if object has named object for debugging
attribute
reversed() Reverse iterator
hash() Hash value of object
round() Number rounded to ndigits
help() Built-in help system precision after decimal
point
hex() Convert integer to
lowercase hexadecimal
string

1 Apr 2024 | Python 3.8+ © kieranholland.com 19 of 23


The Best* Python Cheat Sheet

set() New set object sum() Sums items of iterable


setattr() Set object attribute super() Proxy object that
value by name delegates method calls to
parent or sibling
slice() Slice object representing
a set of indices tuple() Create a tuple
sorted() New sorted list from the type() Type of an object
items in iterable
vars() dict attribute for any
staticmethod() Transform method into other object with a dict
static method attribute
str() String description of zip() Iterate over multiple
object iterables in parallel

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 '%'

20 of 23 © kieranholland.com Python 3.8+ | 1 Apr 2024


The Best* Python Cheat Sheet

Exception

try:

[except [Exception [as e]]:
…]
[except: # catch all
…]
[else: # if no exception
…]
[finally: # always executed
…]

raise exception [from None] # stop exception chain

try:
1 / 0
except ZeroDivisionError:
raise TypeError("Stop chain") from None

1 Apr 2024 | Python 3.8+ © kieranholland.com 21 of 23


The Best* Python Cheat Sheet

BaseException Base class for all exceptions


├─ BaseExceptionGroup Base class for groups of exceptions
├─ GeneratorExit Generator close() raises to terminate iteration
├─ KeyboardInterrupt On user interrupt key (often 'CTRL-C')
├─ SystemExit On sys.exit()
└─ Exception Base class for errors
├─ ArithmeticError Base class for arithmetic errors
│ ├─ FloatingPointError Floating point operation failed
│ ├─ OverflowError Result too large
│ └─ ZeroDivisionError Argument of division or modulo is 0
├─ AssertionError Assert statement failed
├─ AttributeError Attribute reference or assignment failed
├─ BufferError Buffer operation failed
├─ EOFError input() hit end-of-file without reading data
├─ ExceptionGroup Group of exceptions raised together
├─ ImportError Import statement failed
│ └─ ModuleNotFoundError Module not able to be found
├─ LookupError Base class for lookup errors
│ └─ IndexError Index not found in sequence
│ └─ KeyError Key not found in dictionary
├─ MemoryError Operation ran out of memory
├─ NameError Local or global name not found
│ └─ UnboundLocalError Local variable value not asssigned
├─ OSError System related error
│ ├─ BlockingIOError Non-blocking operation will block
│ ├─ ChildProcessError Operation on child process failed
│ ├─ ConnectionError Base class for connection errors
│ │ ├─ BrokenPipeError Write to closed pipe or socket
│ │ ├─ ConnectionAbortedError Connection aborted
│ │ ├─ ConnectionRefusedError Connection denied by server
│ │ └─ ConnectionResetError Connection reset mid-operation
│ ├─ FileExistsError Trying to create a file that already exists
│ ├─ FileNotFoundError File or directory not found
│ ├─ InterruptedError System call interrupted by signal
│ ├─ IsADirectoryError File operation requested on a directory
│ ├─ NotADirectoryError Directory operation requested on a non-directory
│ ├─ PermissionError Operation has insuffient access rights
│ ├─ ProcessLookupError Operation on process that no longer exists
│ └─ TimeoutError Operation timed out
├─ ReferenceError Weak reference used on garbage collected object
├─ RuntimeError Error detected that doesn't fit other categories
│ ├─ NotImplementedError Operation not yet implemented
│ └─ RecursionError Maximum recursion depth exceeded
├─ StopAsyncIteration Iterator __anext__() raises to stop iteration
├─ StopIteration Iterator next() raises when no more values
├─ SyntaxError Python syntax error
│ └─ IndentationError Base class for indentation errors
│ └─ TabError Inconsistent tabs or spaces
├─ SystemError Recoverable Python interpreter error
├─ TypeError Operation applied to wrong type object
├─ ValueError Operation on right type but wrong value
│ └─ UnicodeError Unicode encoding/decoding error
│ ├─ UnicodeDecodeError Unicode decoding error
│ ├─ UnicodeEncodeError Unicode encoding error
│ └─ UnicodeTranslateError Unicode translation error
└─ Warning Base class for warnings
├─ BytesWarning Warnings about bytes and bytesarrays
├─ DeprecationWarning Warnings about deprecated features
├─ EncodingWarning Warning about encoding problem
├─ FutureWarning Warnings about future deprecations for end users
├─ ImportWarning Possible error in module imports
├─ PendingDeprecationWarning Warnings about pending feature deprecations
├─ ResourceWarning Warning about resource use
├─ RuntimeWarning Warning about dubious runtime behavior
├─ SyntaxWarning Warning about dubious syntax
├─ UnicodeWarning Warnings related to Unicode
└─ UserWarning Warnings generated by user code

22 of 23 © kieranholland.com Python 3.8+ | 1 Apr 2024


The Best* Python Cheat Sheet

Execution

$ python [-bBdEhiIOqsSuvVWx?] [-c command | -m module-name | script | - ] [args]


$ python --version
Python 3.10.12
$ python --help[-all] # help-all [3.11+]
# Execute code from command line
$ python -c 'print("Hello, world!")'
# Execute __main__.py in directory
$ python <directory>
# Execute module as __main__
$ python -m timeit -s 'setup here' 'benchmarked code here'
# Optimise execution
$ python -O script.py

# Hide warnings
PYTHONWARNINGS="ignore"
# OR
$ python -W ignore foo.py
# OR
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)

if __name__ == '__main__': # run main() if file executed as script


main()

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

# Get user site packages directory


$ python -m site --user-site

# Bypass sitecustomize.py/usercustomize.py hooks


$ python -S script.py

1 Apr 2024 | Python 3.8+ © kieranholland.com 23 of 23

You might also like