Show Menu
Cheatography

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

Strings

"­"
empty string
len(value)
built-in to get the length
s[start:stop:step]
slicing, start/­sto­p/step are optional, stop is non-in­clusive
s.enco­de(­'ut­f-8')
utf-8 encoded version of s, bytes object
b"st­rin­g"
bytes object

Tuples

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

Lists

[]
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)

Dictio­naries

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

Sets

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

Conditions

if condition:
    stuff
else:
    stuff

if condition:
    stuff
elif condition2:
    stuff
elif condition3:
    stuff
else:
    stuff

ternary = a if condition else b

Iteration

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

for value in [sequence]:
    stuff

for position, value in enumerate(sequence):
    stuff

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

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

while condition:
    stuff
else
    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

Exceptions

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

Functions

def function_name(args):
  body
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
func(*n)
calls func unpacking array argument
def func(**­kw­args):
variable keyword arguments, addressed as a dict
func(**n)
calls func unpacking dict argument
pass
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"""
  pass
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

Utilities

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
zip(*i­ter­ables)
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

Compre­hen­sions

list
[ 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]
dict
 { key_ex­pre­ssion: value_­exp­ression for iterab­le_­clause if option­al_­filter}
set
{ 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
next(f­unc­tion)
resumes execution (or start the first time)
until loop ends with no value or StopIt­eration is raised
genera­tor.se­nd(x)
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

Decorators

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
@wrap
def to_decorate(...):
	#body


from functools import wraps
@wraps(func)
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


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

Classes

class Child(Parent):
is-a inheri­tance
class Child(­Mul­tiple, Parent):
Child.m­ro()
returns Method Resolution Order
def __init­(self, args):
initia­lizer
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
@stati­cmethod
annotation for static method, no special argument (like
self
)
@classmethod
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)
_attribute
pseudo private attribute (conve­ntion)
__some­_at­tr_­or_­method
almost private through name mangling
@property
for getter
@prope­rty.setter
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:
           
 

Comments

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