Show Menu
Cheatography

Python Basics Cheat Sheet (DRAFT) by

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Basic Operations

type(x)
int/fl­oat­/bo­ol/­str­/co­mplex
bin(x)
binary
hex(x)
hexade­cimal
1e8
1*108
inf
infinity
NaN
not a number
abs(x)
absolute value
x//3
floor division
x *= 2
x = x*2
3 % 2
remainder
a ** x
ax
&
and
|
or
^
xor
==
check for equality (->­bool)
!=
not equal
range(­start, finish, stepsize)
includes start, excludes finish

files

f = open('­fil­e.txt', 'w')
opens the file
'w' = write&read
'r' = read
f.writ­e('This is a file')
f.open
f.close
f.flush
can be removed safely now
f.read­line()
reads first line
f.read­line(x)
reads first x positions
f = open(<pa­th>, 'w')
for line in f:
 
code

f.close()

control structures

if x = y:
 command
elif:
else:
if condition
break
ends innermost loop
if x=y and y<z:
two conditions
for i in range(10):
for loop
while i < 5:
while loop
my_iter =
my_list.__iter__()
creates an iterator
next(my_iter)
my_ite­r._­_ne­xt__()
gets next element from iter

vectors & matrices

import numpy as np
v = np.arr­ay([[3, 2]])

note: np.arr­ay([3, 2]) is a rank 1 array, NOT a math. vector
Vectors are lists of lists
v.T
transpose
v.shape
returns dimensions
np.linalg.norm(v){{nl]]or
math.sqrt(dot(v.T,v))
length of vector
A = np.arr­ay(­[[1­,2]­,[3­,4]])
creates a matrix
 
np.ran­dom.ra­nd(2,2)
random matrix
values normal distri­bution 0 to 1
np.ran­dom.ra­ndn­(2,2)
normal distri­bution (mean 0, variance 1)
A.dtype
specif­ically for np
A.ndim
number of dimensions
np.ara­nge(x)
range as array with x elements
np.ide­nti­ty(x)
identity matrix
np.zer­os(­(x,y))
zeros matrix
A[0]
first row
A[0][0] or A[0, 0]
first element of first row
A[:, 0]
first column
A[1:4, 0]
slicing
A[1:, 1:3] = 9
assigning to parts of the matrix
Slicing in python creates copy
In numpy it doesn't!
np.ful­l((2, 3), x)
2by3 matrix filled with x
view = A[0:3,2:4]
writing into a view changes underlying data
view1 = A[0:3,­2:4­].copy
writing doesn't change data
np.whe­re(­A<0, 0, A)
condition, then, else
np.c_[A[:, 0:1], A[:,2:6]]
stack slices horizo­ntally
 

strings

s = input(­"­enter here")
prompts input
s = 'x'; s = "­x"
are both strings
s[0]
returns character at first position
s[0:5]
slicing
s = 'I\'m fine'
escape
s = "­"­"long string­"­"­"­"
enables linebreak
print(s)
\n
linebreak
+
links strings (creates a copy)
s =
'{0}, beautiful {1}!'.f­or­mat­('H­ell­o',­'Wo­rld')
s.find­('x')
returns postion of first occurance
s.repl­ace­('l­','p')
replace all
s.split
returns list of words
len('s­tring')
length
s[i]
retrieves character at position i
s[-1]
retrieves last character
s[i:j]
range i:j

lists

Same functions as strings
l = [index0, index1]
create list
l[i]
retrieves index i
l[i] = x
stores x to index i
l.inse­rt(­ind­ex,­'st­ring')
doesn't remove
l.append
add to end
l.sort
smallest to largest
l.reverse
l.remo­ve(­'st­ring')
or del l[i]
removes first occurance
b = a.copy()
change in a doesn't effect b
b = a
change in a effects b

tuples

t = ('super', 'man')
create tuple
len(t)
returns number of items
t.count(3)
returns number of 3s
x,y = t
tuple unpacking
x = t[0]; y = t[1]
tuples are immutable lists
tuples can't have one number, (1) is a math operation

functions

def my_fct(var_a, var_b):
defines function
return(result)
outputs result for further use
No typech­ecking in functions (duckt­yping)
Keep scope in mind (var_a and var_b are local variables and are destroyed after functions runs
If local variable has same name as global variable, the local one will be referred to when name is used
Pitfall:
print = 5
-> predefined functions can be overwriten

lambda & mapping

lambda a, b: a + b
small nameless function that can be applied to lists etc.
e.g.
sorted­(list, key=lambda x: x[1])
map
e.g.
list(m­ap(­lambda x: x + 10, values))
filter
for filtering lists, e.g.:
list(f­ilt­er(­lambda x: x % 2 == 0, values))

operations for Vectors & matrices

np.dot(v, w)
dot product
np.lin­alg.no­rm(v)
length of vector
is3 = (A == 3)
A > 0
returns boolean matrix
A[A < 0] = 0
replaces entries where conditions is met (true)
np.lin­alg.so­lve(A, b)
solves system of linear equations
np.mean(v)
A.mean(0)

0 for col max, 1 for row max
np.max­imum(v, w)
v.std()
standard deviation
v.sort()
np.vst­ack(A, B)
np.hstack(A, B)
vertic­all­y/h­ori­zontaly stack arrays

numpy analytics

np.min­imu­m.a­ccu­mul­ate­(array)
minimum up until an entry
np.arg­max­(array)
index of max
 

math basics

a = 2 + 3j
complex num
from math import pi
Ï€
from math import exp
ex
np.abs(v)
np.sqrt(v)
np.exp(v)
np.log2(v)
np.sin(v)

dictionary

d = {'x' : 'y', 'a' : 'b'}
key:value
d['x']
returns 'y'
'y' in d
returns bool
d.keys()
returns ['x', 'a']
d.values()
returns ['y', 'b']
d.items()
returns [('x':­'y'), ('a':'b')]
d['tea'] = 'Tee'
add item
d[('su­per', 'man')] = 'Super­mann'
tuples as immutable lists
del d[k]
key can only occur once, values can occur multiple times
(keys need to map to one value)
key: must be immutable (int, float, str, tuple (not list))
value: any data type

sets

s = {1, 2, 3}
create set
s | s2
or s.unio­n(s2)
all elements of both sets
s ^ s2
or s.symm­etr­ic_­dif­fer­enc­e(s2)
elements that are in either s or s2
s & s2
or
s.intersection(s2)
common elements
s <= s2
or s.issu­bse­t(s2)
test if all elements of s is in s2 (bool)
s - s2
or s.diff­ere­nce(s2)
elements in s but not in s2
no order
identical items are combined to one item

logging

import logging
from logging import debug
logger = loggin­g.g­etl­ogger()
logger.se­tLe­vel­(lo­ggi­ng.D­EBUG)
activates logger
debug(­'St­art')
returns message with some stats
loggin­g.d­isa­ble()
all loggers (incl debug) turned off
loggin­g.d­isa­ble­(lo­ggi­ng.N­OTSET)
all loggers reacti­vated
try:
 
command

except:
 print('oops')
or
except IndexError:
 print('Index not found')
dealing with exceptions
raise Exception ('message')
creates an exception
assert x>0, 'No neg. numbers'
returns error if assertion not met

other

np.rep­eat(1, 10)
array with ten 1s
np.asa­rray(list)
converts list to array
np.pol­yfit(x_array, y_array, degree)
fits a polynomial the points (x/y), minimizing the squared error
np.pol­yval(coeff_­array, x_eval­_array)
evaluates a polynomial with given coeffi­cients (sortet highest degree to lowest!) at a number of x-point
reverse_a = a[::-1]

general numpy

np.ran­dom.ra­ndi­nt(­low=0, high=10, size=20)