Mohan pd.
Mohan pd. Author of The Coders Blog. Also a professional fullstack javascript developer working with various tech company and client around world.

Comprehensive Python Cheat Sheet | 2019 | Coders Blog

Sep 14, 2019 · 4 minutes
Comprehensive Python Cheat Sheet | 2019 | Coders Blog

Here are the Comprehensive cheat sheets for python.

Content

Main
if __name__ == '__main__':     # Runs main() if file wasn't imported.
    main()
List
<list> = <list>[from_inclusive : to_exclusive : ±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>)
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 dict and set.
Dictionary
<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.
Counter
>>> 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()
<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>
<set>.remove(<el>)                            # Raises KeyError.
<set>.discard(<el>)                           # 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.
<frozenset> = frozenset(<collection>)

Tuple

Tuple is an immutable and hashable list.

<tuple> = ()
<tuple> = (<el>, )
<tuple> = (<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)
Point(x=1, y=2)
>>> p[0]
1
>>> p.x
1
>>> getattr(p, 'y')
2
>>> p._fields  # Or: Point._fields
('x', 'y')
Range
<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>.stop
Enumerate
for i, el in enumerate(<collection> [, i_start]):
    ...
Iterator
<iter> = iter(<collection>)                 # Calling `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.
Itertools
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)
Generator
  • Convenient way to implement the iterator protocol.
  • Any function that contains a yield statement returns a generator object.
  • 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)