Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://gto76.github.io/python-cheatsheet/

Comprehensive Python Cheatsheet
https://gto76.github.io/python-cheatsheet/

cheatsheet python python-cheatsheet reference

Last synced: about 2 months ago
JSON representation

Comprehensive Python Cheatsheet

Awesome Lists containing this project

README

        

Comprehensive Python Cheatsheet
===============================
[Download text file](https://raw.githubusercontent.com/gto76/python-cheatsheet/main/README.md), [Buy PDF](https://transactions.sendowl.com/products/78175486/4422834F/view), [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-1)**__,__ **[`Combinatorics`](#combinatorics)**__,__ **[`Datetime`](#datetime)**__.__
**   ** **3. Syntax:** **         ** **[`Args`](#arguments)**__,__ **[`Inline`](#inline)**__,__ **[`Import`](#imports)**__,__ **[`Decorator`](#decorator)**__,__ **[`Class`](#class)**__,__ **[`Duck_Types`](#duck-types)**__,__ **[`Enum`](#enum)**__,__ **[`Exception`](#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:** **   ** **[`Threading`](#threading)**__,__ **[`Operator`](#operator)**__,__ **[`Match_Stmt`](#match-statement)**__,__ **[`Logging`](#logging)**__,__ **[`Introspection`](#introspection)**__,__ **[`Coroutines`](#coroutines)**__.__
**   ** **7. Libraries:** **      ** **[`Progress_Bar`](#progress-bar)**__,__ **[`Plots`](#plot)**__,__ **[`Tables`](#table)**__,__ **[`Curses`](#curses)**__,__ **[`GUIs`](#pysimplegui)**__,__ **[`Scraping`](#scraping)**__,__ **[`Web`](#web)**__,__ **[`Profiling`](#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 next line if file was imported.
main() # Runs `def main(): ...` function.
```

List
----
```python
= [index] # First index is 0. Last -1. Allows assignments.
= [] # Or: [from_inclusive : to_exclusive : ±step]
```

```python
.append() # Or: += []
.extend() # Or: +=
```

```python
.sort() # Sorts in ascending order.
.reverse() # Reverses the list in-place.
= sorted() # Returns a new sorted list.
= reversed() # Returns reversed iterator.
```

```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, el: out * el, )
list_of_chars = list()
```
* **For details about sorted(), min() and max() see [sortable](#sortable).**
* **Module [operator](#operator) provides functions itemgetter() and mul() that offer the same functionality as [lambda](#lambda) expressions above.**

```python
= len() # Returns number of items. Also works on other collections.
= .count() # Returns number of occurrences. Also `if in : ...`.
= .index() # Returns index of the first occurrence or raises ValueError.
= .pop() # Removes and returns item from the end or at index if passed.
.insert(, ) # Inserts item at index and moves the rest to the right.
.remove() # Removes first occurrence of the item or raises ValueError.
.clear() # Removes all items. Also works on dictionary and set.
```

Dictionary
----------
```python
= .keys() # Coll. of keys that reflects changes.
= .values() # Coll. of values that reflects changes.
= .items() # Coll. of key-value tuples that reflects chgs.
```

```python
value = .get(key, default=None) # Returns default if key is missing.
value = .setdefault(key, default=None) # Returns and writes default if key is missing.
= collections.defaultdict() # Returns a dict with default value `()`.
= collections.defaultdict(lambda: 1) # Returns a dict with default value 1.
```

```python
= 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
.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} # Filters the dictionary by keys.
```

### Counter
```python
>>> from collections import Counter
>>> counter = Counter(['blue', 'blue', 'blue', 'red', 'red'])
>>> counter['yellow'] += 1
>>> print(counter)
Counter({'blue': 3, 'red': 2, 'yellow': 1})
>>> counter.most_common()[0]
('blue', 3)
```

Set
---
```python
= set() # `{}` returns a dictionary.
```

```python
.add() # Or: |= {}
.update( [, ...]) # Or: |=
```

```python
= .union() # Or: |
= .intersection() # Or: &
= .difference() # Or: -
= .symmetric_difference() # Or: ^
= .issubset() # Or: <=
= .issuperset() # Or: >=
```

```python
= .pop() # Raises KeyError if empty.
.remove() # Raises KeyError if missing.
.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
= () # Empty tuple.
= (,) # Or: ,
= (, [, ...]) # Or: , [, ...]
```

### Named Tuple
**Tuple's subclass with named elements.**
```python
>>> from collections import namedtuple
>>> Point = namedtuple('Point', 'x y')
>>> p = Point(1, y=2); p
Point(x=1, y=2)
>>> p[0]
1
>>> p.x
1
>>> getattr(p, 'y')
2
```

Range
-----
**Immutable and hashable sequence of integers.**
```python
= range(stop) # range(to_exclusive)
= range(start, stop) # range(from_inclusive, to_exclusive)
= range(start, stop, ±step) # 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 iterator of `(index+start, )` tuples.
...
```

Iterator
--------
```python
= iter() # `iter()` returns unmodified iterator.
= iter(, to_exclusive) # A sequence of return values until 'to_exclusive'.
= next( [, default]) # Raises StopIteration or returns 'default' on end.
= list() # Returns a list of iterator's remaining elements.
```

### Itertools
```python
import itertools as it
```

```python
= it.count(start=0, step=1) # Returns updated value endlessly. Accepts floats.
= it.repeat( [, times]) # Returns element endlessly or 'times' times.
= it.cycle() # Repeats the sequence endlessly.
```

```python
= it.chain(, [, ...]) # Empties collections in order (figuratively).
= it.chain.from_iterable() # Empties collections inside a collection in order.
```

```python
= it.islice(, to_exclusive) # Only returns first 'to_exclusive' elements.
= it.islice(, from_inc, …) # `to_exclusive, +step_size`. Indices 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 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 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
= .strip() # Strips all whitespace characters from both ends.
= .strip('') # Strips passed characters. Also lstrip/rstrip().
```

```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) # On [\n\r\f\v\x1c-\x1e\x85\u2028\u2029] and \r\n.
= .join() # Joins elements using string as a separator.
```

```python
= in # Checks if string contains the substring.
= .startswith() # Pass tuple of strings for multiple options.
= .find() # Returns start index of the first match or -1.
= .index() # Same, but raises ValueError if there's no match.
```

```python
= .lower() # Changes the case. Also upper/capitalize/title().
= .replace(old, new [, count]) # Replaces 'old' with 'new' at most 'count' times.
= .translate() # Use `str.maketrans()` to generate table.
```

```python
= chr() # Converts int to Unicode character.
= ord() # Converts Unicode character to int.
```
* **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.**

### Property Methods
```python
= .isdecimal() # Checks for [0-9]. Also [०-९] and [٠-٩].
= .isdigit() # Checks for [²³¹…] and isdecimal().
= .isnumeric() # Checks for [¼½¾], [零〇一…] and isdigit().
= .isalnum() # Checks for [a-zA-Z…] and isnumeric().
= .isprintable() # Checks for [ !#$%…] and isalnum().
= .isspace() # Checks for [ \t\n\r\f\v\x1c-\x1f\x85\xa0…].
```

Regex
-----
**Functions for regular expression matching.**

```python
import re
= re.sub(r'', new, text, count=0) # Substitutes all occurrences with 'new'.
= re.findall(r'', text) # Returns all occurrences as strings.
= re.split(r'', text, maxsplit=0) # Add brackets around regex to keep matches.
= re.search(r'', text) # First occurrence of the pattern or None.
= re.match(r'', text) # Searches only at the beginning 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.**
* **Argument `'flags=re.MULTILINE'` makes `'^'` and `'$'` match the start/end of each line.**
* **Argument `'flags=re.DOTALL'` makes `'.'` also accept the `'\n'`.**
* **`'re.compile()'` returns a Pattern object with methods sub(), findall(), …**

### Match Object
```python
= .group() # Returns the whole match. Also group(0).
= .group(1) # Returns part inside the first brackets.
= .groups() # Returns all bracketed parts.
= .start() # Returns start index of the match.
= .end() # Returns exclusive end index of the match.
```

### Special Sequences
```python
'\d' == '[0-9]' # Also [०-९…]. Matches a decimal character.
'\w' == '[a-zA-Z0-9_]' # Also [ª²³…]. Matches an alphanumeric or _.
'\s' == '[ \t\n\r\f\v]' # Also [\x1c-\x1f…]. Matches a whitespace.
```

* **By default, decimal characters, alphanumerics and whitespaces from all alphabets are matched unless `'flags=re.ASCII'` argument is used.**
* **It restricts special sequence matches to `'[\x00-\x7f]'` (the first 128 characters) and also prevents `'\s'` from accepting `'[\x1c-\x1f]'` (the so-called separator characters).**
* **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(, ) # Or: '{0}, {a}'.format(, a=)
= '%s, %s' % (, ) # Redundant and inferior C-style formatting.
```

### Example
```python
>>> Person = collections.namedtuple('Person', 'name height')
>>> person = Person('Jean-Luc', 187)
>>> f'{person.name} is {person.height / 100} meters tall.'
'Jean-Luc is 1.87 meters tall.'
```

### General Options
```python
{:<10} # ' '
{:^10} # ' '
{:>10} # ' '
{:.<10} # '......'
{:0} # ''
```
* **Objects are rendered using `'format(