Download text file, PDF, Fork me on GitHub or Check out FAQ.
1. Collections: List, Dictionary, Set, Tuple, Range, Enumerate, Iterator, Generator.
2. Types: Type, String, Regular_Exp, Format, Numbers, Combinatorics, Datetime.
3. Syntax: Args, Inline, Closure, Decorator, Class, Duck_Types, Enum, Exceptions.
4. System: Print, Input, Command_Line_Arguments, Open, Path, Command_Execution.
5. Data: CSV, JSON, Pickle, SQLite, Bytes, Struct, Array, MemoryView, Deque.
6. Advanced: Threading, Operator, Introspection, Metaprograming, Eval, Coroutine.
7. Libraries: Progress_Bar, Plot, Table, Curses, Logging, Scraping, Web, Profile,
NumPy, Image, Audio.
if __name__ == '__main__': # Runs main() if file wasn't imported.
main()<list> = <list>[from_inclusive : to_exc
B2EA
lusive : ±step_size]<list>.append(<el>) # Or: <list> += [<el>]
<list>.extend(<collection>) # Or: <list> += <collection><list>.sort()
<list>.reverse()
<list> = sorted(<collection>)
<iter> = reversed(<list>)sum_of_elements = sum(<collection>)
elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)]
sorted_by_second = sorted(<collection>, key=lambda el: el[1])
sorted_by_both = sorted(<collection>, key=lambda el: (el[1], el[0]))
flatter_list = list(itertools.chain.from_iterable(<list>))
product_of_elems = functools.reduce(lambda out, x: out * x, <collection>)
list_of_chars = list(<str>)<int> = <list>.count(<el>) # Returns number of occurrences. Also works on strings.
index = <list>.index(<el>) # Returns index of first occurrence or raises ValueError.
<list>.insert(index, <el>) # Inserts item at index and moves the rest to the right.
<el> = <list>.pop([index]) # Removes and returns item at index or from the end.
<list>.remove(<el>) # Removes first occurrence of item or raises ValueError.
<list>.clear() # Removes all items. Also works on dictionary and set.<view> = <dict>.keys() # Coll. of keys that reflects changes.
<view> = <dict>.values() # Coll. of values that reflects changes.
<view> = <dict>.items() # Coll. of key-value tuples.value = <dict>.get(key, default=None) # Returns default if key does not exist.
value = <dict>.setdefault(key, default=None) # Same, but also adds default to dict.
<dict> = collections.defaultdict(<type>) # Creates a dict with default value of type.
<dict> = collections.defaultdict(lambda: 1) # Creates a dict with default value 1.<dict>.update(<dict>)
<dict> = dict(<collection>) # Creates a dict from coll. of key-value pairs.
<dict> = dict(zip(keys, values)) # Creates a dict from two collections.
<dict> = dict.fromkeys(keys [, value]) # Creates a dict from collection of keys.value = <dict>.pop(key) # Removes item or raises KeyError.
{k: v for k, v in <dict>.items() if k in keys} # Filters dictionary by keys.>>> 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> = set()<set>.add(<el>) # Or: <set> |= {<el>}
<set>.update(<collection>) # Or: <set> |= <set><set> = <set>.union(<coll.>) # Or: <set> | <set>
<set> = <set>.intersection(<coll.>) # Or: <set> & <set>
<set> = <set>.difference(<coll.>) # Or: <set> - <set>
<set> = <set>.symmetric_difference(<coll.>) # Or: <set> ^ <set>
<bool> = <set>.issubset(<coll.>) # Or: <set> <= <set>
<bool> = <set>.issuperset(<coll.>) # Or: <set> >= <set><el> = <set>.pop() # Raises KeyError if empty.
<set>.remove(<el>) # Raises KeyError if missing.
<set>.discard(<el>) # Doesn't raise an error.- Is immutable and hashable.
- That means it can be used as a key in a dictionary or as an element in a set.
<frozenset> = frozenset(<collection>)Tuple is an immutable and hashable list.
<tuple> = ()
<tuple> = (<el>, )
<tuple> = (<el_1>, <el_2>, ...)Tuple's subclass with named elements.
>>> 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> = range(to_exclusive)
<range> = range(from_inclusive, to_exclusive)
<range> = range(from_inclusive, to_exclusive, ±step_size)from_inclusive = <range>.start
to_exclusive = <range>.stopfor i, el in enumerate(<collection> [, i_start]):
...<iter> = iter(<collection>) # `iter(<iter>)` returns unmodified iterator.
<iter> = iter(<function>, to_exclusive) # Sequence of return values until 'to_exclusive'.
<el> = next(<iter> [, default]) # Raises StopIteration or returns 'default' on end.from itertools import count, repeat, cycle, chain, islice<iter> = count(start=0, step=1) # Returns incremented value endlessly.
<iter> = repeat(<el> [, times]) # Returns element endlessly or 'times' times.
<iter> = cycle(<collection>) # Repeats the sequence indefinitely.<iter> = chain(<coll.>, <coll.> [, ...]) # Empties collections in order.
<iter> = chain.from_iterable(<collection>) # Empties collections inside a collection in order.<iter> = islice(<collection>, to_exclusive)
<iter> = islice(<collection>, from_inclusive, to_exclusive)
<iter> = islice(<collection>, from_inclusive, to_exclusive, +step_size)- 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>>> counter = count(10, 2)
>>> next(counter), next(counter), next(counter)
(10, 12, 14)- Everything is an object.
- Every object has a type.
- Type and class are synonymous.
<type> = type(<el>) # Or: <el>.__class__
<bool> = isinstance(<el>, <type>) # Or: issubclass(type(<el>), <type>)>>> type('a'), 'a'.__class__, str
(<class 'str'>, <class 'str'>, <class 'str'>)from types import FunctionType, MethodType, LambdaType, GeneratorTypeAn abstract base class introduces virtual subclasses, that don’t inherit from it but are still recognized by isinstance() and issubclass().
>>> from collections.abc import Sequence, Collection, Iterable
>>> isinstance([1, 2, 3], Iterable)
True+------------------+----------+------------+----------+
| | Sequence | Collection | Iterable |
+------------------+----------+------------+----------+
| list, range, str | yes | yes | yes |
| dict, set | | yes | yes |
| iter | | | yes |
+------------------+----------+------------+----------+
>>> from numbers import Integral, Rational, Real, Complex, Number
>>> isinstance(123, Number)
True+--------------------+----------+----------+--------+---------+--------+
| | Integral | Rational | Real | Complex | Number |
+--------------------+----------+----------+--------+---------+--------+
| int | yes | yes | yes | yes | yes |
| fractions.Fraction | | yes | yes | yes | yes |
| float | | | yes | yes | yes |
| complex | | | | yes | yes |
| decimal.Decimal | | | | | yes |
+--------------------+----------+----------+--------+---------+--------+
<str> = <str>.strip() # Strips all whitespace characters from both ends.
<str> = <str>.strip('<chars>') # Strips all passed characters from both ends.<list> = <str>.split() # Splits on one or more whitespace characters.
<list> = <str>.split(sep=None, maxsplit=-1) # Splits on 'sep' str at most 'maxsplit' times.
<list> = <str>.splitlines(keepends=False) # Splits on line breaks. Keeps them if 'keepends'.
<str> = <str>.join(<coll_of_strings>) # Joins elements using string as separator.<bool> = <sub_str> in <str> # Checks if string contains a substring.
<bool> = <str>.startswith(<sub_str>) # Pass tuple of strings for multiple options.
<bool> = <str>.endswith(<sub_str>) # Pass tuple of strings for multiple options.
<int> = <str>.find(<sub_str>) # Returns start index of first match or -1.
<int> = <str>.index(<sub_str>) # Same but raises ValueError.<str> = <str>.replace(old, new [, count]) # Replaces 'old' with 'new' at most 'count' times.
<bool> = <str>.isnumeric() # True if str contains only numeric characters.
<list> = textwrap.wrap(<str>, width) # Nicely breaks string into lines.- Also:
'lstrip()','rstrip()'. - Also:
'lower()','upper()','capitalize()'and'title()'.
<str> = chr(<int>) # Converts int to unicode char.
<int> = ord(<str>) # Converts unicode char to int.>>> ord('0'), ord('9')
(48, 57)
>>> ord('A'), ord('Z')
(65, 90)
>>> ord('a'), ord('z')
(97, 122)import re
<str<
2742
/span>> = re.sub(<regex>, new, text, count=0) # Substitutes all occurrences.
<list> = re.findall(<regex>, text) # Returns all occurrences.
<list> = re.split(<regex>, text, maxsplit=0) # Use brackets in regex to keep the matches.
<Match> = re.search(<regex>, text) # Searches for first occurrence of pattern.
<Match> = re.match(<regex>, text) # Searches only at the beginning of the text.
<iter> = re.finditer(<regex>, text) # Returns all occurrences as match objects.- Search() and match() return None if there are no matches.
- 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. - Add
'?'after an operator to make it non-greedy.
<str> = <Match>.group() # Whole match. Also group(0).
<str> = <Match>.group(1) # Part in first bracket.
<tuple> = <Match>.groups() # All bracketed parts.
<int> = <Match>.start() # Start index of a match.
<int> = <Match>.end() # Exclusive end index of a match.- By default digits, whitespaces and alphanumerics from all alphabets are matched, unless
'flags=re.ASCII'argument is used. - Use capital letters for negation.
'\d' == '[0-9]' # Digit
'\s' == '[ \t\n\r\f\v]' # Whitespace
'\w' == '[a-zA-Z0-9_]' # Alphanumeric<str> = f'{<el_1>}, {<el_2>}'
<str> = '{}, {}'.format(<el_1>, <el_2>)