The project's README from github.com/gto76/python-cheatsheet. As one markdown file: README.md.
Download text file, Fork me on GitHub or Check out FAQ.

1. Collections: List, Dictionary, Set, Tuple, Range, Enumerate, Iterator, Generator.
2. Data Types: Type, String, Regular_Exp, Format, Numbers, Combinatorics, Datetime.
3. Syntax Rules: Function, Inline, Import, Decorator, Class, Duck_Type, Enum, Except.
4. System Calls: Exit, Print, Input, Command_Line_Arguments, Open, Path, OS_Commands.
5. Data Formats: JSON, Pickle, CSV, SQLite, Bytes, Struct, Array, Memory_View, Deque.
6. Misc Topics: Operator, Match_Statement, Logging, Introspection, Threads, Asyncio.
7. Pip Packages: Progress_Bar, Plot, Table, Console_App, GUI, Scraping, Web, Profile.
8. Multimedia: NumPy, Image, Animation, Audio, Synthesizer, Pygame, Pandas, Plotly.
if __name__ == '__main__': # Skips indented lines of code if file was imported.
main() # Executes user-defined `def main(): ...` function.
<list> = [<el>, <el>, ...] # Creates new list object. E.g. `list_a = [1, 2, 3]`.
<el> = <list>[index] # First index is 0, last -1. Also `<list>[i] = <el>`.
<list> = <list>[<slice>] # Also <list>[from_inclusive : to_exclusive : ±step].
<list>.append(<el>) # Appends element to the end. Or `<list> += [<el>]`.
<list>.extend(<coll>) # Appends collection's items. Or `<list> += <coll>`.
<list>.sort() # Sorts in ascending order. Accepts `reverse=True`.
<list>.reverse() # Reverses the order of elements. Takes linear time.
<list> = sorted(<coll>) # Returns a new sorted list. Accepts `reverse=True`.
<iter> = reversed(<list>) # Returns reversed iterator. Also list(<iterator>).
<el> = max(<coll>) # Returns the largest element. Also min(<el>, <el>).
<num> = sum(<coll>) # Returns a sum of elements. Also math.prod(<coll>).
elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)]
sorted_by_second = sorted(<coll>, key=lambda pair: pair[1])
sorted_by_both = sorted(<coll>, key=lambda p: (p[1], p[0]))
flatter_list = list(itertools.chain.from_iterable(<list>))
<int> = len(<list/dict/set/…>) # Returns number of items. Doesn't accept iterators.
<int> = <list>.count(<el>) # Counts occurrences. Also `if <el> in <coll>: ...`.
<int> = <list>.index(<el>) # Returns index of first occ. or raises ValueError.
<el> = <list>.pop() # Removes item from the end (or at index if passed).
<list>.insert(<int>, <el>) # Inserts item at index and shifts remaining items.
<list>.remove(<el>) # Removes the first occurrence or raises ValueError.
<list>.clear() # Removes all items. Also provided by dict and set.
<dict> = {key: val, key: val, ...} # Use `<dict>[key]` to get or assign the value.
<view> = <dict>.keys() # A collection of keys reflecting all changes.
<view> = <dict>.values() # A collection of values that reflects changes.
<view> = <dict>.items() # Coll. of tuples. Each contains key and value.
value = <dict>.get(key, default=None) # Returns 'default' argument if key is missing.
value = <dict>.setdefault(key, default) # Returns/writes 'default' when key is missing.
<dict> = collections.defaultdict(<type>) # Dict with automatic default value `<type>()`.
<dict> = dict(<collection>) # Creates a dict from coll. of key-value pairs.
<dict> = dict(zip(keys, values)) # Creates key-value pairs from two collections.
<dict> = dict.fromkeys(keys [, value]) # Items get value None if only keys are passed.
<dict>.update(<dict>) # Adds items to dict. Passed dict has priority.
value = <dict>.pop(key) # Removes item or raises KeyError when missing.
{k for k, v in <dict>.items() if v == 123} # Returns a set of keys whose value equals 123.
{k: v for k, v in <dict>.items() if k in ks} # Returns a dict of items with specified keys.
>>> from collections import Counter
>>> counter = Counter(['blue', 'blue', 'red'])
>>> counter['yellow'] += 3
>>> print(counter.most_common())
[('yellow', 3), ('blue', 2), ('red', 1)]
<set> = {<el>, <el>, ...} # Coll. of unique items. Also set(), set(<coll>).
<set>.add(<el>) # Adds item to the set. Same as `<set> |= {<el>}`.
<set>.update(<coll> [, ...]) # Adds items to the set. Same as `<set> |= <set>`.
<set> = <set>.union(<coll>) # Returns a set of all items. Also <set> | <set>.
<set> = <set>.intersection(<coll>) # Returns every shared item. Also <set> & <set>.
<set> = <set>.difference(<coll>) # Returns set's unique items. Also <set> - <set>.
<bool> = <set>.issuperset(<coll>) # Returns False when collection has unique items.
<bool> = <set>.issubset(<coll>) # Is collection a superset? Also <set> <= <set>.
<el> = <set>.pop() # Removes one of items. Raises KeyError if empty.
<set>.remove(<el>) # Removes the item or raises KeyError if missing.
<set>.discard(<el>) # Same as remove() but it doesn't raise an error.
<frozenset> = frozenset(<collection>)
Tuple is an immutable and hashable list.
<tuple> = () # Returns an empty tuple. Also tuple(), tuple(<coll>).
<tuple> = (<el>,) # Returns tuple with one element. Or `<tup.> = <el>,`.
<tuple> = (<el>, <el> [, ...]) # Returns a tuple. Or `<tuple> = <el>, <el> [, ...]`.
Tuple's subclass with named elements.
>>> import collections as co
>>> Point = co.namedtuple('Point', 'x y')
>>> p = Point(1, y=2)
>>> print(p)
Point(x=1, y=2)
>>> p.x, p[1]
(1, 2)
A sequence of evenly spaced integers.
<range> = range(stop) # I.e. range(to_exclusive). Ints from 0 to `stop-1`.
<range> = range(start, stop) # I.e. range(from, to_exc). From start to `stop-1`.
<range> = range(start, stop, step) # I.e. range(from_inclusive, to_exclusive, ±step).
>>> [i for i in range(3)]
[0, 1, 2]
Iterator that zips collection with range.
for i, el in enumerate(<coll>):
print(f'Element {el} has index {i}.')
Potentially endless stream of elements.
import itertools as it
<iter> = iter(<coll>) # Iterator that returns passed elements one by one.
<iter> = iter(<func>, to_exc) # Calls `<func>()` until it receives 'to_exc' value.
<iter> = (<expr> for <name> in <coll>) # E.g. `(i+1 for i in range(3))`. Evaluates lazily.
<el> = next(<iter> [, default]) # Raises StopIteration or returns 'default' on end.
<list> = list(<iter>) # Returns a list of iterator's remaining elements.
<iter> = it.count(start=0, step=1) # Returns updated 'start' endlessly. Accepts floats.
<iter> = it.repeat(<obj> [, times]) # Returns passed element endlessly or 'times' times.
<iter> = it.cycle(<coll>) # Repeats the sequence endlessly. Accepts iterators.
<iter> = it.chain(<coll>, <coll>, ...) # Returns each element of each collection in order.
<iter> = it.chain.from_iterable(<coll>) # Accepts collection (i.e. iterable) of collections.
<iter> = it.islice(<coll>, stop) # Also accepts 'start' and 'step'. Args can be None.
<iter> = it.product(<coll>, <coll>) # Same as `((a, b) for a in arg_1 for b in arg_2)`.
'iter(<coll/iter>)', latter returning unmodified iterator.def count(start, step):
while True:
yield start
start += step
>>> counter = count(10, 2)
>>> next(counter), next(counter), next(counter)
(10, 12, 14)
<type> = type(<obj>) # Object's type. Also `<obj>.__class__`.
<bool> = isinstance(<obj>, <type>) # Also `issubclass(type(<obj>), <type>)`.
>>> type('a'), 'a'.__class__, str
(<class 'str'>, <class 'str'>, <class 'str'>)
from types import FunctionType, MethodType, LambdaType, GeneratorType
Each abstract base class specifies a set of virtual subclasses. These classes are then recognized by isinstance() and issubclass() as subclasses of the ABC, although they are really not. An ABC can also manually decide whether or not a specific class is its virtual subclass, usually based on which methods that class has implemented. For instance, Iterable ABC looks for method iter(), while Collection ABC looks for iter(), contains() and len().
>>> from collections.abc import Iterable, Collection, Sequence
>>> isinstance([1, 2, 3], Iterable)
True
+------------------+------------+------------+------------+
| | Iterable | Collection | Sequence |
+------------------+------------+------------+------------+
| list, range, str | yes | yes | yes |
| dict, set | yes | yes | |
| iter | yes | | |
+------------------+------------+------------+------------+
>>> from numbers import Number, Complex, Real, Rational, Integral
>>> isinstance(123, Number)
True
+--------------------+---------+---------+--------+----------+----------+
| | Number | Complex | Real | Rational | Integral |
+--------------------+---------+---------+--------+----------+----------+
| int | yes | yes | yes | yes | yes |
| fractions.Fraction | yes | yes | yes | yes | |
| float | yes | yes | yes | | |
| complex | yes | yes | | | |
| decimal.Decimal | yes | | | | |
+--------------------+---------+---------+--------+----------+----------+
Immutable sequence of characters.
<str> = 'abc' # Also "abc". Interprets \n, \t, \x00-\xff, etc.
<str> = <str>.strip() # Strips all whitespace characters from both ends.
<str> = <str>.strip('<chars>') # Strips passed characters. Also lstrip/rstrip().
<list> = <str>.split() # Splits it on one or more whitespace characters.
<list> = <str>.split(<str>) # Splits on passed string. Also `maxsplit=<int>`.
<list> = <str>.splitlines() # On [\n\r\f\v\x1c-\x1e\x85\u2028\u2029] and \r\n.
<str> = <str>.join(<coll_of_str>) # Joins items by using the string as a separator.
<bool> = <str> in <str> # Returns True if string contains the substring.
<bool> = <str>.startswith(<str>) # Pass tuple of strings to give multiple options.
<int> = <str>.find(<str>) # Returns start index of the first match or `-1`.
<str> = <str>.lower() # Lowers the case. Also upper/capitalize/title().
<str> = <str>.casefold() # Lower() that converts ẞ/ß to ss, Σ/ς to σ, etc.
<str> = <str>.replace(old, new) # Removes occurrences of string old if new is ''.
<str> = <str>.translate(table) # Get table via str.maketrans(<chr_to_str_dict>).
<str> = chr(<int>) # Converts passed integer into Unicode character.
<int> = ord(<str>) # Converts passed Unicode character into integer.
'unicodedata.normalize("NFC", <str>)' on strings like 'Motörhead' before comparing them to other strings, because 'ö' can be stored as one or two characters.'NFC' converts such characters to a single character, while 'NFD' converts them to two.<bool> = <str>.isdecimal() # Checks all chars for [0-9]. Also [०-९], [٠-٩].
<bool> = <str>.isdigit() # Checks for [²³¹…] and isdecimal(). Also [፩-፱].
<bool> = <str>.isnumeric() # Checks for [¼½¾…] and isdigit(). Also [零〇一…].
<bool> = <str>.isalnum() # Checks for [ABC…] and isnumeric(). Also [ªµº…].
<bool> = <str>.isprintable() # Checks for [ !"#…], basic emojis and isalnum().
<bool> = <str>.isspace() # Checks for [ \t\n\r\f\v\x1c\x1d\x1e\x1f\x85…].
Functions for regular expression matching.
import re
<str> = re.sub(r'<regex>', new, text) # Substitutes occurrences with string 'new'.
<list> = re.findall(r'<regex>', text) # Returns all occurrences as string objects.
<list> = re.split(r'<regex>', text) # Add brackets around regex to keep matches.
<Match> = re.search(r'<regex>', text) # Returns first occ. of the pattern or None.
<Match> = re.match(r'<regex>', text) # Only searches at the start of the 'text'.
<iter> = re.finditer(r'<regex>', text) # Returns all occurrences as Match objects.
'new' can also be a function that accepts a Match object and returns a string.'flags=re.IGNORECASE' can be used with all functions that are listed above.'flags=re.MULTILINE' makes '^' and '$' match the start/end of each line.'flags=re.DOTALL' makes '.' also accept the '\n' (besides all other chars).'re.compile(r"<regex>")' returns a Pattern object with methods sub(), findall(), etc.<str> = <Match>.group() # Returns the whole match. Also group(0).
<str> = <Match>.group(1) # Returns part inside the first brackets.
<tuple> = <Match>.groups() # Returns all bracketed parts as strings.
<int> = <Match>.start() # Returns start index of the whole match.
<int> = <Match>.end() # Returns the match's end index plus one.
'\d' == '[0-9]' # Also [०-९…]. Matches decimal character.
'\w' == '[a-zA-Z0-9_]' # Also [ª²³…]. Matches alphanumeric or _.
'\s' == '[ \t\n\r\f\v]' # Also [\x1c-\x1f…]. Matches whitespace.
'flags=re.ASCII' is used. It restricts special sequence matches to the first 128 Unicode characters and also prevents '\s' from accepting '\x1c', '\x1d', '\x1e' and '\x1f' (non-printable characters that divide text into files, tables, rows and fields, respectively).'\D', '\W' or '\S', for negation. All non-ASCII characters are matched if ASCII flag is used in conjunction with a capital letter.String formatting mechanisms.
<str> = f'{<obj>}, {<obj>}' # Braces can also contain expressions.
<str> = '{}, {}'.format(<obj>, <obj>) # Or '{0}, {a}'.format(<obj>, a=<obj>).
<str> = '%s, %s' % (<obj>, <obj>) # Old and redundant formatting method.
>>> Person = collections.namedtuple('Person', 'name height')
>>> jean = Person('Jean-Luc', 187)
>>> f'{jean.name} is {jean.height / 100} meters tall.'
'Jean-Luc is 1.87 meters tall.'
{<obj>:<10} # '<obj> '.
{<obj>:^10} # ' <obj> '.
{<obj>:>10} # ' <obj>'.
{<obj>:.<10} # '<obj>.....'.
{<obj>:0} # '<obj>'.
'format(<obj>, "<10")'.f'{<obj>:{<str/int>}[…]}'.'=' to the expression prepends it to its result, e.g. f'{1+1=}' returns '1+1=2'.'!r' to the expression first calls result's repr() method and only then format().{'abcde':10} # 'abcde '.
{'abcde':10.3} # 'abc '.
{'abcde':.3} # 'abc'.
{'abcde'!r:10} # "'abcde' ".
{123456:10} # ' 123456'.
{123456:10,} # ' 123,456'.
{123456:10_}