Comprehensive Python Cheatsheet
===============================
[Download text file](https://raw.githubusercontent.com/gto76/python-cheatsheet/master/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).
![Monty Python](web/image_888.jpeg)
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)**__,__ **[`Combinatorics`](#combinatorics)**__,__ **[`Datetime`](#datetime)**__.__
** ** **3. Syntax:** ** ** **[`Args`](#arguments)**__,__ **[`Inline`](#inline)**__,__ **[`Closure`](#closure)**__,__ **[`Decorator`](#decorator)**__,__ **[`Class`](#class)**__,__ **[`Duck_Types`](#duck-types)**__,__ **[`Enum`](#enum)**__,__ **[`Exceptions`](#exceptions)**__.__
** ** **4. System:** ** ** **[`Print`](#print)**__,__ **[`Input`](#input)**__,__ **[`Command_Line_Arguments`](#command-line-arguments)**__,__ **[`Open`](#open)**__,__ **[`Path`](#path)**__,__ **[`Command_Execution`](#command-execution)**__.__
** ** **5. Data:** ** ** **[`CSV`](#csv)**__,__ **[`JSON`](#json)**__,__ **[`Pickle`](#pickle)**__,__ **[`SQLite`](#sqlite)**__,__ **[`Bytes`](#bytes)**__,__ **[`Struct`](#struct)**__,__ **[`Array`](#array)**__,__ **[`MemoryView`](#memory-view)**__,__ **[`Deque`](#deque)**__.__
** ** **6. Advanced:** ** ** **[`Threading`](#threading)**__,__ **[`Introspection`](#introspection)**__,__ **[`Metaprograming`](#metaprograming)**__,__ **[`Operator`](#operator)**__,__ **[`Eval`](#eval)**__,__ **[`Coroutine`](#coroutine)**__.__
** ** **7. Libraries:** ** ** **[`Progress_Bar`](#progress-bar)**__,__ **[`Plot`](#plot)**__,__ **[`Table`](#table)**__,__ **[`Curses`](#curses)**__,__ **[`Logging`](#logging)**__,__ **[`Scraping`](#scraping)**__,__ **[`Web`](#web)**__,__ **[`Profile`](#profile)**__,__
** ** **[`NumPy`](#numpy)**__,__ **[`Image`](#image)**__,__ **[`Audio`](#audio)**__.__
Main
----
```python
if __name__ == '__main__': # Runs main() if file wasn't imported.
main()
```
List
----
```python
= [from_inclusive : to_exclusive : ±step_size]
```
```python
.append() # Or: += []
.extend() # Or: +=
```
```python
.sort()
.reverse()
= sorted()
= reversed()
```
```python
sum_of_elements = sum()
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())
product_of_elems = functools.reduce(lambda out, x: out * x, )
list_of_chars = list()
```
```python
index = .index() # Returns index of first occurrence or raises ValueError.
.insert(index, ) # Inserts item at index and moves the rest to the right.
= .pop([index]) # Removes and returns item at index or from the end.
.remove() # Removes first occurrence of item or raises ValueError.
.clear() # Removes all items. Also works on dict and set.
```
Dictionary
----------
```python
= .keys() # Coll. of keys that reflects changes.
= .values() # Coll. of values that reflects changes.
= .items() # Coll. of key-value tuples.
```
```python
value = .get(key, default=None) # Returns default if key does not exist.
value = .setdefault(key, default=None) # Same, but also adds default to dict.
= collections.defaultdict() # Creates a dict with default value of type.
= collections.defaultdict(lambda: 1) # Creates a dict with default value 1.
```
```python
.update()
= dict() # Creates a dict from coll. of key-value pairs.
= dict(zip(keys, values)) # Creates a dict from two collections.
= dict.fromkeys(keys [, value]) # Creates a dict from collection of keys.
```
```python
value = .pop(key) # Removes item from dictionary.
{k: v for k, v in .items() if k in keys} # Filters dictionary by keys.
```
### Counter
```python
>>> from collections import Counter
>>> colors = ['red', 'blue', 'yellow', 'blue', 'red', 'blue']
>>> counter = Counter(colors)
Counter({'blue': 3, 'red': 2, 'yellow': 1})
>>> counter.most_common()[0]
('blue', 3)
```
Set
---
```python
= set()
```
```python
.add() # Or: |= {}
.update() # Or: |=
```
```python
= .union() # Or: |
= .intersection() # Or: &
= .difference() # Or: -
= .symmetric_difference() # Or: ^
= .issubset() # Or: <=
= .issuperset() # Or: >=
```
```python
.remove() # Raises KeyError.
.discard() # 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 element in a set.**
```python
= frozenset()
```
Tuple
-----
**Tuple is an immutable and hashable list.**
```python
= ()
= (, )
= (, , ...)
```
### Named Tuple
**Tuple's subclass with named elements.**
```python
>>> from collections import namedtuple
>>> Point = namedtuple('Point', 'x y')
>>> p = Point(1, y=2)
Point(x=1, y=2)
>>> p[0]
1
>>> p.x
1
>>> getattr(p, 'y')
2
>>> p._fields # Or: Point._fields
('x', 'y')
```
Range
-----
```python
= range(to_exclusive)
= range(from_inclusive, to_exclusive)
= range(from_inclusive, to_exclusive, ±step_size)
```
```python
from_inclusive = .start
to_exclusive = .stop
```
Enumerate
---------
```python
for i, el in enumerate( [, i_start]):
...
```
Iterator
--------
```python
= iter() # Calling `iter()` returns unmodified iterator.
= iter(, to_exclusive) # Sequence of return values until 'to_exclusive'.
= next( [, default]) # Raises StopIteration or returns 'default' on end.
```
### Itertools
```python
from itertools import count, repeat, cycle, chain, islice
```
```python
= count(start=0, step=1) # Returns incremented value endlessly.
= repeat( [, times]) # Returns element endlessly or 'times' times.
= cycle() # Repeats the sequence indefinitely.
```
```python
= chain(, [, ...]) # Empties collections in order.
= chain.from_iterable() # Empties collections inside a collection in order.
```
```python
= islice(, to_exclusive)
= islice(, from_inclusive, to_exclusive)
= islice(, from_inclusive, to_exclusive, +step_size)
```
Generator
---------
* **Convenient way to implement the iterator protocol.**
* **Any function that contains a yield statement returns a generator object.**
* **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 is an object.**
* **Every object has a type.**
* **Type and class are synonymous.**
```python
= type() # Or: .__class__
= isinstance(, ) # Or: issubclass(type(), )
```
```python
>>> type('a'), 'a'.__class__, str
(, , )
```
#### Some types do not have builtin names, so they must be imported:
```python
from types import FunctionType, MethodType, LambdaType, GeneratorType
```
### ABC
**An abstract base class introduces virtual subclasses, that don’t inherit from it but are still recognized by isinstance() and issubclass().**
```python
>>> from collections.abc import Sequence, Collection, Iterable
>>> isinstance([1, 2, 3], Iterable)
True
```
```text
+------------------+----------+------------+----------+
| | Sequence | Collection | Iterable |
+------------------+----------+------------+----------+
| list, range, str | yes | yes | yes |
| dict, set | | yes | yes |
| iter | | | yes |
+------------------+----------+------------+----------+
```
```python
>>> from numbers import Integral, Rational, Real, Complex, Number
>>> isinstance(123, Number)
True
```
```text
+--------------------+----------+----------+------+---------+--------+
| | Integral | Rational | Real | Complex | Number |
+--------------------+----------+----------+------+---------+--------+
| int | yes | yes | yes | yes | yes |
| fractions.Fraction | | yes | yes | yes | yes |
| float | | | yes | yes | yes |
| complex | | | | yes | yes |
+--------------------+----------+----------+------+---------+--------+
```
String
------
```python
= .strip() # Strips all whitespace characters from both ends.
= .strip('') # Strips all passed characters from both ends.
```
```python
= .split() # Splits on one or more whitespace characters.
= .split(sep=None, maxsplit=-1) # Splits on 'sep' str at most 'maxsplit' times.
= .splitlines(keepends=False) # Splits on line breaks. Keeps them if 'keepends'.
= .join() # Joins elements using string as separator.
```
```python
= in # Checks if string contains a substring.
= .startswith() # Pass tuple of strings for multiple options.
= .endswith() # Pass tuple of strings for multiple options.
= .find() # Returns start index of first match or -1.
= .index() # Same but raises ValueError.
```
```python
= .replace(old, new [, count]) # Replaces 'old' with 'new' at most 'count' times.
= .isnumeric() # True if str contains only numeric characters.
= textwrap.wrap(, width) # Nicely breaks string into lines.
```
* **Also: `'lstrip()'`, `'rstrip()'`.**
* **Also: `'lower()'`, `'upper()'`, `'capitalize()'` and `'title()'`.**
### Char
```python
= chr() # Converts int to unicode char.
= ord() # Converts unicode char to int.
```
```python
>>> ord('0'), ord('9')
(48, 57)
>>> ord('A'), ord('Z')
(65, 90)
>>> ord('a'), ord('z')
(97, 122)
```
Regex
-----
```python
import re
= re.sub(, new, text, count=0) # Substitutes all occurrences.
= re.findall(, text) # Returns all occurrences.
= re.split(, text, maxsplit=0) # Use brackets in regex to keep the matches.
= re.search(, text) # Searches for first occurrence of pattern.
= re.match(, text) # Searches only at the beginning of the text.
= re.finditer(, text) # Returns all occurrences as match objects.
```
* **Argument `'flags=re.IGNORECASE'` can be used with all functions.**
* **Argument `'flags=re.MULTILINE'` makes `'^'` and `'$'` match the start/end of each line.**
* **Argument `'flags=re.DOTALL'` makes dot also accept newline.**
* **Use `r'\1'` or `'\\1'` for backreference.**
* **Use `'?'` to make an operator non-greedy.**
### Match Object
```python
= .group() # Whole match. Also group(0).
= .group(1) # Part in first bracket.
= .groups() # All bracketed parts.
= .start() # Start index of a match.
= .end() # Exclusive end index of a match.
```
### Special Sequences
* **By default digits, whitespaces and alphanumerics from all alphabets are matched, unless `'flags=re.ASCII'` argument is used.**
* **Use capital letters for negation.**
```python
'\d' == '[0-9]' # Digit
'\s' == '[ \t\n\r\f\v]' # Whitespace
'\w' == '[a-zA-Z0-9_]' # Alphanumeric
```
Format
------
```python
= f'{}, {}'
= '{}, {}'.format(, )
```
### Attributes
```python
>>> from collections import namedtuple
>>> Person = namedtuple('Person', 'name height')
>>> person = Person('Jean-Luc', 187)
>>> f'{person.height}'
'187'
>>> '{p.height}'.format(p=person)
'187'
```
### General Options
```python
{:<10} # ' '
{:^10} # ' '
{:>10} # ' '
```
```python
{:.<10} # '......'
{:>0} # ''
```
### Strings
**`'!r'` calls object's repr() method, instead of str(), to get a string.**
```python
{'abcde'!r:<10} # "'abcde' "
{'abcde':.3} # 'abc'
{'abcde':10.3} # 'abc '
```
### Numbers
```python
{ 123456:10,} # ' 123,456'
{ 123456:10_} # ' 123_456'
{ 123456:+10} # ' +123456'
{-123456:=10} # '- 123456'
{ 123456: } # ' 123456'
{-123456: } # '-123456'
```
### Floats
```python
{1.23456:10.3} # ' 1.23'
{1.23456:10.3f} # ' 1.235'
{1.23456:10.3e} # ' 1.235e+00'
{1.23456:10.3%} # ' 123.456%'
```
#### Comparison of float presentation types:
```text
+----------------+----------------+---------------+----------------+-----------------+
| | {} | {:f} | {:e} | {:%} |
+----------------+----------------+---------------+----------------+-----------------+
| 0.000056789 | '5.6789e-05' | '0.000057' | '5.678900e-05' | '0.005679%' |
| 0.00056789 | '0.00056789' | '0.000568' | '5.678900e-04' | '0.056789%' |
| 0.0056789 | '0.0056789' | '0.005679' | '5.678900e-03' | '0.567890%' |
| 0.056789 | '0.056789' | '0.056789' | '5.678900e-02' | '5.678900%' |
| 0.56789 | '0.56789' | '0.567890' | '5.678900e-01' | '56.789000%' |
| 5.6789 | '5.6789' | '5.678900' | '5.678900e+00' | '567.890000%' |
| 56.789 | '56.789' | '56.789000' | '5.678900e+01' | '5678.900000%' |
| 567.89 | '567.89' | '567.890000' | '5.678900e+02' | '56789.000000%' |
+----------------+----------------+---------------+----------------+-----------------+
```
```text
+----------------+----------------+---------------+----------------+-----------------+
| | {:.2} | {:.2f} | {:.2e} | {:.2%} |
+----------------+----------------+---------------+----------------+-----------------+
| 0.000056789 | '5.7e-05' | '0.00' | '5.68e-05' | '0.01%' |
| 0.00056789 | '0.00057' | '0.00' | '5.68e-04' | '0.06%' |
| 0.0056789 | '0.0057' | '0.01' | '5.68e-03' | '0.57%' |
| 0.056789 | '0.057' | '0.06' | '5.68e-02' | '5.68%' |
| 0.56789 | '0.57' | '0.57' | '5.68e-01' | '56.79%' |
| 5.6789 | '5.7' | '5.68' | '5.68e+00' | '567.89%' |
| 56.789 | '5.7e+01' | '56.79' | '5.68e+01' | '5678.90%' |
| 567.89 | '5.7e+02' | '567.89' | '5.68e+02' | '56789.00%' |
+----------------+----------------+---------------+----------------+-----------------+
```
### Ints
```python
{90:c} # 'Z'
{90:X} # '5A'
{90:b} # '1011010'
```
Numbers
-------
```python
= int() # Or: math.floor()
= float()
= complex(real=0, imag=0) # Or: + j
= fractions.Fraction(numerator=0, denominator=1)
```
* **`'int()'` and `'float()'` raise ValueError on malformed strings.**
### Basic Functions
```python
= pow(, ) # Or: **
= abs()
= round()
= round(, ±ndigits) # `round(126, -1) == 130`
```
### Math
```python
from math import e, pi, inf, nan
from math import cos, acos, sin, asin, tan, atan, degrees, radians
from math import log, log10, log2
```
### Statistics
```python
from statistics import mean, median, variance, pvariance, pstdev
```
### Random
```python
from random import random, randint, choice, shuffle
= random()
= randint(from_inclusive, to_inclusive)
= choice()
shuffle()
```
### Bin, Hex
```python
= 0b