Show Menu

Python 3 Core Cheat Sheet by

Virtual Enviro­nment setup

sudo pip install virtualenv # sudo may by optional
mkdir testenv
cd testenv
virtualenv -p $( which python3.4 ) .lpvenv
source .lpven­v/b­in/­act­ivate
This set of commands is for a unix-like enviro­nment, but a similar setup can be done on Windows.

Core types

Integers: unlimited
cast: int(value)
Boolean: True/False
cast: bool(v­alue)
any non-zero is True
Real: 64 bits
Decimal: arbitrary precision
from decimal import Decimal
Complex: 1 + 2j
methods: real, imag


empty string
built-in to get the length
slicing, start/­sto­p/step are optional, stop is non-in­clusive
utf-8 encoded version of s, bytes object
bytes object


empty tuple
1-element tuple, comma is required
generic syntax for tuples
a,b,c = 1,2,3
implicit on assignment
Tuples are immutable


[] or list()
empty list
list((­create, from, a, tuple))
[x + 5 for x in (1,2,3)]
definition by compre­hension
concat­enate lists
repeat list
Notable methods: append(x), count(x), extend(list), index(x), insert(pos,value), pop(), pop(pos), remove(val), reverse(), sort(), clear()
Notable functions: min(list), max(list), sum(list), len(list)


dict() or {}
empty dictionary
Equivalent defini­tions
dict(A=1, Z=-1)
{'A': 1, 'Z': -1}
dict(z­ip(­['A', 'Z'], [1, -1]))
dict([­('A', 1), ('Z', -1)])
dict({'Z': -1, 'A': 1})
Notable operations: len, del, in
Notable methods: clear(), keys(), values(), items(), popitem(), pop(key), update({key, value}), update(key=value), get(key), setdefault


empty set
value in set
test for presence
Mutable, for immutable, use frozenset.
Notable methods: add(x), remove(x)


if condition:

if condition:
elif condition2:
elif condition3:

ternary = a if condition else b


for i in range(start,stop,step):

for value in [sequence]:

for position, value in enumerate(sequence):

for a,b in zip(first, second):

for ###
    stuff to do at end of loop (usually exception when breaking in loop)

while condition:
    stuff to do when condition is false

break # breaks the loop
continue # continue at the start of the loop body
module itertools provides lots of intere­sting tools for iteration


    # do something
  except ExceptionName as e:
    # do something
  except (ExceptionName, OtherException) as e:
    # do something
    # do something when no exception
    # do something anyway, exception or not


def function_name(args):
nonlocal variab­le_name
access to nearest enclosing scope for variable
global variab­le_name
access global scope variable
def func(a­,b,c):
standard positional args
func(c=1, b=2, a=3)
call using keywords
def func(a­,b=­55,­c=85:)
default values for missing args, !! be wary of mutable defaults
def func(*n):
variable arg list, addressed as an array
calls func unpacking array argument
def func(**­kw­args):
variable keyword arguments, addressed as a dict
calls func unpacking dict argument
empty body method
return a,b,c
return multiple values
lambda [param­ete­r_l­ist]: expression
for small snippets
def func(n):
  """documentation, possibly multiline"""
Special attributes: __doc__, __name__, __qualname__, __module__, __defaults__, __code__, __globals__, __dict__, __closure__, __annotations__, __kwdefaults__
builtins: abs all any ascii bin callable chr compile delattr dir divmod eval exec format getattr globals hasattr hash hex id input isinstance issubclass iter len locals max min next oct open ord pow print repr round setattr sorted sum vars


map(fu­nction, iterable, option­al_­ite­rable, ...)
returns iterator which will apply function on each value of the iterables, stopping at first exhausted iterable
returns iterator of tuples, interl­acing the iterables, stops at first exhausted iterable
filter­(fu­nction, iterable)
returns iterator from those elements of iterable for which function returns True


[ expression for iterab­le_­clause if option­al_­filter]
nested lists
[ expression for iterab­le_­cla­use_1 for iterab­le_­cla­use_2 if option­al_­filter]
{ key_ex­pre­ssion: value_­exp­ression for iterab­le_­clause if option­al_­filter}
{ value_­exp­ression for iterab­le_­clause if option­al_­filter}

Generator functions

yield x
returns the value x, suspends and stores the internal state
resumes execution (or start the first time)
until loop ends with no value or StopIt­eration is raised
resumes and makes x as the return value of yield
usage example: for in in genera­tor­_fu­nct­ion­(**­som­e_p­arams)
yield from list_c­omp­reh­ension
advanced pattern

Generator expression

like a list compre­hension but ( ) instead of []
returns 1 item at a time
easier to read than map+filter


def wrap(func):
    def wrapper(*args, **kwargs):
        # do something about func
        func(*args, **kwargs)
        # do something about func
    return wrapper

# Apply decorator
def to_decorate(...):
	# body	
to_decorate = wrap(to_decorate)	

# More idiomatic
def to_decorate(...):

from functools import wraps
def wrapper(...) # to keep the name and doc from the wrapped function

# Decorator with args: make a decorator factory
def decorator_factory(factory_args):
    def decorator(func):
        def wrapper(*args, **kwargs):
            # do something about func
            func(*args, **kwargs)
            # do something about func
        return wrapper
    return decorator

def to_decorate(...):
Multiple decora­tors: the closer the decorator to the function, the sooner it is applied.


class Child(Parent):
is-a inheri­tance
class Child(­Mul­tiple, Parent):
Child.m­ro() returns Method Resolution Order
def __init­(self, args):
super(­)._­_in­it_­_(self, some_args)
call parent initia­lizer
def instan­ce_­met­hod­(self, args):
self is a convention for the first argument, the implicit instance
instance = ClassN­ame­(pa­rams)
create instance
annotation for static method, no special argument (like self)
annotation for static method, special argument is the class object itself (conve­ntion: cls). Usage: factory methods or extracting sub-me­thods from @stati­cme­thods methods (to avoid having a hard-coded class name when calling them)
pseudo private attribute (conve­ntion)
almost private through name mangling
for getter
for setter
a class is a subclass of itself; attributes can be added in declar­ation (class attrib­utes) or dynami­cally to instance or class

Custom Iteration

iterable must define __iter__ or __get_­item__
iterator must define __iter__ (returning self) and __next__ (raise StopIt­eration at the end)
usage: for i in iterable:


No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

            Python 3 Cheat Sheet by Finxter