Comprehensive Python Cheatsheet
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>))
…
<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 | | |
+------------------+------------+------------+-----