if __name__ == '__main__': # Skips indented lines of code if file was imported.
main() # Executes user-defined `def main(): ...` function.
List
<list> = [<el_1>, <el_2>, ...] # 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. Also `<list> += [<el>]`.
<list>.extend(<collection>) # Appends multiple elements. Also `<list> += <coll>`.
<list>.sort(reverse=False) # Sorts the elements of the list in ascending order.
<list>.reverse() # Reverses the order of elements. Takes linear time.
<list> = sorted(<collection>) # Returns a new sorted list. Accepts `reverse=True`.
<iter> = reversed(<list>) # Returns reversed iterator. Also list(<iterator>).
<el> = max(<collection>) # Returns the largest element. Also min(<el_1>, ...).
<num> = sum(<collection>) # Returns a sum of elements. Also math.prod(<coll>).
For details about sort(), sorted(), min() and max() see Sortable.
Module operator has function itemgetter() that can replace listed lambdas.
This text uses the term collection instead of iterable. For rationale see duck types.
<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.
Dictionary
<dict> = {key_1: val_1, key_2: val_2, ...} # Use `<dict>[key]` to get or assign the value.
<view> = <dict>.keys() # A collection of keys that reflects changes.
<view> = <dict>.values() # A collection of values that reflects changes.
<view> = <dict>.items() # Coll. of key-value tuples that reflects chgs.
value = <dict>.get(key, default=None) # Returns argument default if key is missing.
value = <dict>.setdefault(key, default=None) # Returns and writes default if key is missing.
<dict> = collections.defaultdict(<type>) # Dict with automatic default value `<type>()`.
<dict> = collections.defaultdict(lambda: 1) # Dictionary with automatic default value `1`.
<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 keys} # Returns a dict of items with specified keys.
<set> = {<el_1>, <el_2>, ...} # Coll. of unique items. Also set(), set(<coll>).
<set>.add(<el>) # Adds item to the set. Same as `<set> |= {<el>}`.
<set>.update(<collection> [, ...]) # 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 all shared items. Also <set> & <set>.
<set> = <set>.difference(<coll>) # Returns set's unique items. Also <set> - <set>.
<set> = <set>.symmetric_diff…(<coll>) # Returns non-shared items. Also <set> ^ <set>.
<bool> = <set>.issuperset(<coll>) # Returns False if collection has unique items.
<bool> = <set>.issubset(<coll>) # Is collection a superset? Also <set> <= <set>.
<el> = <set>.pop() # Removes and returns an item or raises KeyError.
<set>.remove(<el>) # Removes the item or raises KeyError if missing.
<set>.discard(<el>) # Same as remove() but it doesn't raise an error.
Frozen Set
Frozenset is immutable and hashable version of the normal set.
That means it can be used as a key in a dictionary or as an item in a set.
<frozenset> = frozenset(<collection>)
Tuple
Tuple is an immutable and hashable list.
<tuple> = () # Returns an empty tuple. Also tuple(), tuple(<coll>).
<tuple> = (<el>,) # Returns a tuple with single element. Same as `<el>,`.
<tuple> = (<el_1>, <el_2> [, ...]) # Returns a tuple. Same as `<el_1>, <el_2> [, ...]`.
Named Tuple
Tuple’s subclass with named elements.
>>> 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
A sequence of evenly spaced integers.
<range> = range(stop) # I.e. range(to_exclusive). Integers from 0 to `stop-1`.
<range> = range(start, stop) # I.e. range(from_inc, to_exc). From start to `stop-1`.
<range> = range(start, stop, ±step) # I.e. range(from_inclusive, to_exclusive, ±step_size).
>>> [i for i in range(3)]
[0, 1, 2]
Enumerate
for i, el in enumerate(<coll>, start=0): # Returns next element and its index on each pass.
...
Iterator
Potentially endless stream of elements.
<iter> = iter(<collection>) # 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.
For loops call 'iter(<collection>)' at the start and 'next(<iter>)' on each pass.
Calling 'iter(<iter>)' returns unmodified iterator. For details see Iterator duck type.
<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)`.
Generator
Any function that contains a yield statement returns a generator.
Generators and iterators are interchangeable.
def count(start, step):
while True:
yield start
start += step
Some types do not have built-in names, so they must be imported:
from types import FunctionType, MethodType, LambdaType, GeneratorType
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. 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().
<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(sep=None, maxsplit=-1) # Splits on 'sep' string at most 'maxsplit' times.
<list> = <str>.splitlines(keepends=False) # On [\n\r\f\v\x1c-\x1e\x85\u2028\u2029] and \r\n.
<str> = <str>.join(<coll_of_strings>) # Joins items by using the string as a separator.
<bool> = <sub_str> in <str> # Returns True if string contains the substring.
<bool> = <str>.startswith(<sub_str>) # Pass tuple of strings to give multiple options.
<int> = <str>.find(<sub_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 [, count]) # Replaces 'old' with 'new' at most 'count' times.
<str> = <str>.translate(table) # Use `str.maketrans(<dict>)` to generate table.
<str> = chr(<int>) # Converts passed integer into Unicode character.
<int> = ord(<str>) # Converts passed Unicode character into integer.
Use '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…].
Regex
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.
Raw string literals do not interpret escape sequences, thus enabling us to use the regex-specific escape sequences that cause SyntaxWarning in normal string literals (since 3.12).
Argument 'new' can also be a function that accepts a Match object and returns a string.
Argument 'flags=re.IGNORECASE' can be used with all functions that are listed above.
Comprehensive Python Cheatsheet
Download text file, Fork me on GitHub or Check out FAQ.
Contents
1. Collections:
List,Dictionary,Set,Tuple,Range,Enumerate,Iterator,Generator.2. Types:
Type,String,Regular_Exp,Format,Numbers,Combinatorics,Datetime.3. Syntax:
Function,Inline,Import,Decorator,Class,Duck_Type,Enum,Except.4. System:
Exit,Print,Input,Command_Line_Arguments,Open,Path,OS_Commands.5. Data:
JSON,Pickle,CSV,SQLite,Bytes,Struct,Array,Memory_View,Deque.6. Advanced:
Operator,Match_Statement,Logging,Introspection,Threads,Asyncio.7. Libraries:
Progress_Bar,Plot,Table,Console_App,GUI,Scraping,Web,Profile.8. Multimedia:
NumPy,Image,Animation,Audio,Synthesizer,Pygame,Pandas,Plotly.Main
List
Dictionary
Counter
Set
Frozen Set
Tuple
Tuple is an immutable and hashable list.
Named Tuple
Tuple’s subclass with named elements.
Range
A sequence of evenly spaced integers.
Enumerate
Iterator
Potentially endless stream of elements.
'iter(<collection>)'at the start and'next(<iter>)'on each pass.'iter(<iter>)'returns unmodified iterator. For details see Iterator duck type.Generator
Type
Some types do not have built-in names, so they must be imported:
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. 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().
String
Immutable sequence of characters.
'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.Regex
Functions for regular expression matching.
'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'