Comprehensive Python Cheatsheet
===============================
[Download text file](https://raw.githubusercontent.com/gto76/python-cheatsheet/main/README.md), [Fork me on GitHub](https://github.com/gto76/python-cheatsheet) or [Check out FAQ](https://github.com/gto76/python-cheatsheet/wiki/Frequently-Asked-Questions).

Contents
--------
** ** **1. Collections:** ** ** **[`List`](#list)**__,__ **[`Dictionary`](#dictionary)**__,__ **[`Set`](#set)**__,__ **[`Tuple`](#tuple)**__,__ **[`Range`](#range)**__,__ **[`Enumerate`](#enumerate)**__,__ **[`Iterator`](#iterator)**__,__ **[`Generator`](#generator)**__.__
** ** **2. Types:** ** ** **[`Type`](#type)**__,__ **[`String`](#string)**__,__ **[`Regular_Exp`](#regex)**__,__ **[`Format`](#format)**__,__ **[`Numbers`](#numbers-1)**__,__ **[`Combinatorics`](#combinatorics)**__,__ **[`Datetime`](#datetime)**__.__
** ** **3. Syntax:** ** ** **[`Function`](#function)**__,__ **[`Inline`](#inline)**__,__ **[`Import`](#imports)**__,__ **[`Decorator`](#decorator)**__,__ **[`Class`](#class)**__,__ **[`Duck_Type`](#duck-types)**__,__ **[`Enum`](#enum)**__,__ **[`Except`](#exceptions)**__.__
** ** **4. System:** ** ** **[`Exit`](#exit)**__,__ **[`Print`](#print)**__,__ **[`Input`](#input)**__,__ **[`Command_Line_Arguments`](#command-line-arguments)**__,__ **[`Open`](#open)**__,__ **[`Path`](#paths)**__,__ **[`OS_Commands`](#os-commands)**__.__
** ** **5. Data:** ** ** **[`JSON`](#json)**__,__ **[`Pickle`](#pickle)**__,__ **[`CSV`](#csv)**__,__ **[`SQLite`](#sqlite)**__,__ **[`Bytes`](#bytes)**__,__ **[`Struct`](#struct)**__,__ **[`Array`](#array)**__,__ **[`Memory_View`](#memory-view)**__,__ **[`Deque`](#deque)**__.__
** ** **6. Advanced:** ** ** **[`Operator`](#operator)**__,__ **[`Match_Stmt`](#match-statement)**__,__ **[`Logging`](#logging)**__,__ **[`Introspection`](#introspection)**__,__ **[`Threading`](#threading)**__,__ **[`Coroutines`](#coroutines)**__.__
** ** **7. Libraries:** ** ** **[`Progress_Bar`](#progress-bar)**__,__ **[`Plot`](#plot)**__,__ **[`Table`](#table)**__,__ **[`Console_App`](#console-app)**__,__ **[`GUI`](#gui-app)**__,__ **[`Scraping`](#scraping)**__,__ **[`Web`](#web-app)**__,__ **[`Profile`](#profiling)**__.__
** ** **8. Multimedia:** ** ** **[`NumPy`](#numpy)**__,__ **[`Image`](#image)**__,__ **[`Animation`](#animation)**__,__ **[`Audio`](#audio)**__,__ **[`Synthesizer`](#synthesizer)**__,__ **[`Pygame`](#pygame)**__,__ **[`Pandas`](#pandas)**__,__ **[`Plotly`](#plotly)**__.__
Main
----
```python
if __name__ == '__main__': # Skips indented lines of code if file was imported.
main() # Executes user-defined `def main(): ...` function.
```
List
----
```python
= [, , ...] # Creates new list object. E.g. `list_a = [1, 2, 3]`.
```
```python
= [index] # First index is 0, last -1. Also `[i] = `.
= [] # Also [from_inclusive : to_exclusive : ±step].
```
```python
.append() # Appends element to the end. Also ` += []`.
.extend() # Appends multiple elements. Also ` += `.
```
```python
.sort(reverse=False) # Sorts the elements of the list in ascending order.
.reverse() # Reverses the order of elements. Takes linear time.
= sorted() # Returns a new sorted list. Accepts `reverse=True`.
= reversed() # Returns reversed iterator. Also list().
```
```python
= max() # Returns the largest element. Also min(, ...).
= sum() # Returns a sum of elements. Also math.prod().
```
```python
elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)]
sorted_by_second = sorted(, key=lambda el: el[1])
sorted_by_both = sorted(, key=lambda el: (el[1], el[0]))
flatter_list = list(itertools.chain.from_iterable())
```
* **For details about sort(), sorted(), min() and max() see [Sortable](#sortable).**
* **Module [operator](#operator) has function itemgetter() that can replace listed [lambdas](#lambda).**
* **This text uses the term collection instead of iterable. For rationale see [Collection](#collection).**
```python
= len() # Returns number of items. Doesn't accept iterators.
= .count() # Counts occurrences. Also `if in : ...`.
= .index() # Returns index of first occ. or raises ValueError.
= .pop() # Removes item from the end (or at index if passed).
.insert(, ) # Inserts item at index and shifts remaining items.
.remove() # Removes the first occurrence or raises ValueError.
.clear() # Removes all items. Also provided by dict and set.
```
Dictionary
----------
```python
= {key_1: val_1, key_2: val_2, ...} # Use `[key]` to get or assign the value.
```
```python
= .keys() # A collection of keys that reflects changes.
= .values() # A collection of values that reflects changes.
= .items() # Coll. of key-value tuples that reflects chgs.
```
```python
value = .get(key, default=None) # Returns argument default if key is missing.
value = .setdefault(key, default=None) # Returns and writes default if key is missing.
= collections.defaultdict() # Dict with automatic default value `()`.
= collections.defaultdict(lambda: 1) # Dictionary with automatic default value 1.
```
```python
= dict() # Creates a dict from coll. of key-value pairs.
= dict(zip(keys, values)) # Creates a dictionary from two collections.
= dict.fromkeys(keys [, value]) # Creates a dictionary from collection of keys.
```
```python
.update() # Adds items. Replaces ones with matching keys.
value = .pop(key) # Removes item or raises KeyError if missing.
{k for k, v in .items() if v == value} # Returns set of keys that point to the value.
{k: v for k, v in .items() if k in keys} # Returns a dict of items with specified keys.
```
### Counter
```python
>>> from collections import Counter
>>> counter = Counter(['blue', 'blue', 'blue', 'red', 'red'])
>>> counter['yellow'] += 1
>>> print(counter.most_common())
[('blue', 3), ('red', 2), ('yellow', 1)]
```
Set
---
```python
= {, , ...} # Coll. of unique items. Also set(), set().
```
```python
.add() # Adds item to the set. Same as ` |= {}`.
.update( [, ...]) # Adds items to the set. Same as ` |= `.
```
```python
= .union() # Returns a set of all items. Also | .
= .intersection() # Returns all shared items. Also & .
= .difference() # Returns set's unique items. Also - .
= .symmetric_difference() # Returns non-shared items. Also ^ .
= .issuperset() # Returns False if collection has unique items.
= .issubset() # Is collection a superset? Also <= .
```
```python
= .pop() # Removes and returns an item or raises KeyError.
.remove() # Removes the item or raises KeyError if missing.
.discard() # Same as remove() but it doesn't raise an error.
```
### Frozen Set
* **Is immutable and hashable.**
* **That means it can be used as a key in a dictionary or as an item in a set.**
```python
= frozenset()
```
Tuple
-----
**Tuple is an immutable and hashable list.**
```python
= () # Returns an empty tuple. Also tuple(), tuple().
= (,) # Returns a tuple with single element. Same as `,`.
= (, [, ...]) # Returns a tuple. Same as `, [, ...]`.
```
### Named Tuple
**Tuple's subclass with named elements.**
```python
>>> from collections import namedtuple
>>> Point = namedtuple('Point', 'x y')
>>> p = Point(1, y=2)
>>> print(p)
Point(x=1, y=2)
>>> p.x, p[1]
(1, 2)
```
Range
-----
**Immutable and hashable sequence of integers.**
```python
= range(stop) # I.e. range(to_exclusive). Integers from 0 to `stop-1`.
= range(start, stop) # I.e. range(from_inc, to_exc). From start to `stop-1`.
= range(start, stop, ±step) # I.e. range(from_inclusive, to_exclusive, ±step_size).
```
```python
>>> [i for i in range(3)]
[0, 1, 2]
```
Enumerate
---------
```python
for i, el in enumerate(, start=0): # Returns next element and its index on each pass.
...
```
Iterator
--------
**Potentially endless stream of elements.**
```python
= iter() # Object that iterates over the collection's items.
= iter(, to_exc) # Calls passed function until it returns 'to_exc'.
= ( for in ) # Lazy comprehension. E.g. (i+1 for i in range(3)).
= next() # Returns next element. Raises StopIteration on end.
= list() # Returns a list of iterator's remaining elements.
```
* **For loops call `'iter()'` at the start and `'next()'` on each pass.**
* **Calling `'iter()'` returns unmodified iterator. For details see [Iterator](#iterator-1) duck type.**
```python
import itertools as it
```
```python
= it.count(start=0, step=1) # Returns updated value endlessly. Accepts floats.
= it.repeat( [, times]) # Returns passed element endlessly or 'times' times.
= it.cycle() # Repeats the passed sequence of elements endlessly.
```
```python
= it.chain(, [, ...]) # Empties collections in order (only figuratively).
= it.chain.from_iterable() # Empties collections inside a collection in order.
= it.islice(, [start,] stop) # Also accepts `+step`. Start and stop can be None.
```
Generator
---------
* **Any function that contains a yield statement returns a generator.**
* **Generators and iterators are interchangeable.**
```python
def count(start, step):
while True:
yield start
start += step
```
```python
>>> counter = count(10, 2)
>>> next(counter), next(counter), next(counter)
(10, 12, 14)
```
Type
----
* **Everything in Python is an object.**
* **Every object has a certain type.**
* **Type and class are synonymous.**
```python
= type() # Returns object's type. Same as `.__class__`.
= isinstance(, ) # Same result as `issubclass(type(), )`.
```
```python
>>> type('a'), 'a'.__class__, str
(, , )
```
#### Some types do not have built-in names, so they must be imported:
```python
from types import FunctionType, MethodType, LambdaType, GeneratorType, ModuleType
```
### Abstract Base Classes
**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. ABC can also manually decide whether or not a specific class is its virtual subclass, usually based on which methods the class has implemented. For instance, Iterable ABC looks for method iter(), while Collection ABC looks for iter(), contains() and len().**
```python
>>> from collections.abc import Iterable, Collection, Sequence
>>> isinstance([1, 2, 3], Iterable)
True
```
```text
+------------------+------------+------------+------------+
| | Iterable | Collection | Sequence |
+------------------+------------+------------+------------+
| list, range, str | yes | yes | yes |
| dict, set | yes | yes | |
| iter | yes | | |
+------------------+------------+------------+------------+
```
```python
>>> from numbers import Number, Complex, Real, Rational, Integral
>>> isinstance(123, Number)
True
```
```text
+--------------------+-----------+-----------+----------+----------+----------+
| | 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 | | | | |
+--------------------+-----------+-----------+----------+----------+----------+
```
String
------
**Immutable sequence of characters.**
```python
= 'abc' # Also "abc". Interprets \n, \t, \x00-\xff, etc.
```
```python
= .strip() # Strips all whitespace characters from both ends.
= .strip('') # Strips passed characters. Also lstrip/rstrip().
```
```python
= .split() # Splits it on one or more whitespace characters.
= .split(sep=None, maxsplit=-1) # Splits on 'sep' string at most 'maxsplit' times.
= .splitlines(keepends=False) # On [\n\r\f\v\x1c-\x1e\x85\u2028\u2029] and \r\n.
= .join() # Joins items by using the string as a separator.
```
```python
= in # Returns True if string contains the substring.
= .startswith() # Pass tuple of strings to give multiple options.
= .find() # Returns start index of the first match or -1.
```
```python
= .lower() # Lowers the case. Also upper/capitalize/title().
= .casefold() # Lower() that converts ẞ/ß to ss, Σ/ς to σ, etc.
= .replace(old, new [, count]) # Replaces 'old' with 'new' at most 'count' times.
= .translate(table) # Use `str.maketrans()` to generate table.
```
```python
= chr() # Converts passed integer into Unicode character.
= ord() # Converts passed Unicode character into integer.
```
* **Use `'unicodedata.normalize("NFC", )'` 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.**
```python
= .isdecimal() # Checks all chars for [0-9]. Also [०-९], [٠-٩].
= .isdigit() # Checks for [²³¹…] and isdecimal(). Also [፩-፱].
= .isnumeric() # Checks for [¼½¾…] and isdigit(). Also [零〇一…].
= .isalnum() # Checks for [ABC…] and isnumeric(). Also [ªµº…].
= .isprintable() # Checks for [ !"#$…] and isalnum(). Also emojis.
= .isspace() # Checks for [ \t\n\r\f\v\x1c\x1d\x1e\x1f\x85…].
```
Regex
-----
**Functions for regular expression matching.**
```python
import re
= re.sub(r'', new, text, count=0) # Substitutes every occurrence with 'new'.
= re.findall(r'', text) # Returns every occurrence of the pattern.
= re.split(r'', text, maxsplit=0) # Add brackets around regex to keep matches.
= re.search(r'', text) # Returns first occ. of the pattern or None.
= re.match(r'', text) # Only searches at the start of the 'text'.
= re.finditer(r'', text) # Returns all occurrences as Match objects.
```
* **Raw string literals do not interpret escape sequences, thus enabling us to use regex-specific escape sequences that cause SyntaxWarning in normal string literals (since 3.12).**
* **Argument 'new' of re.sub() can be a function that accepts Match object and returns a str.**
* **Argument `'flags=re.IGNORECASE'` can be used with all functions that are listed above.**
* **Argument `'flags=re.MULTILINE'` makes `'^'` and `'$'` match the start/end of each line.**
* **Argument `'flags=re.DOTALL'` makes `'.'` also accept the `'\n'` (besides all other chars).**
* **`'re.compile()'` returns a Pattern object with methods sub(), findall(), etc.**
### Match Object
```python
= .group() # Returns the whole match. Also group(0).
= .group(1) # Returns part inside the first brackets.
= .groups() # Returns all bracketed parts as strings.
= .start() # Returns start index of the whole match.
= .end() # Returns a match's exclusive end index.
```
### Special Sequences
```python
'\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.
```
* **By default, decimal characters and alphanumerics from all alphabets are matched unless `'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).**
* **Use a capital letter for negation (all non-ASCII characters will be matched when used in combination with ASCII flag).**
Format
------
```perl
= f'{}, {}' # Curly brackets can also contain expressions.
= '{}, {}'.format(,