Python Advance Cheatsheet
Python Advance Cheatsheet
Python Advance Cheatsheet
False, True Data values from the data type False == (1 > 2), True == (2 > 1)
while(True):
continue Finishes current loop iteration continue
print("43") # dead code
class Beer:
class Defines a new class → a real-world concept def __init__(self):
(object oriented programming) self.content = 1.0
def def drink(self):
Defines a new function or class method. For latter,
first parameter (“self”) points to the class object. self.content = 0.0
When calling class method, first parameter is implicit.
becks = Beer() # constructor - create class
becks.drink() # beer empty: b.content == 0
is object
def f():
x = 2
None Empty value constant f() is None # True
def incrementor(x):
lambda Function with no name (anonymous function)
return x + 1
Terminates execution of the function and passes the incrementor(4) # returns 5
flow of execution to the caller. An optional value
return after the return keyword specifies the function
result.
Boolean The Boolean data type is a truth value, either ## 1. Boolean Operations
True or False. x, y = True, False
print(x and not y) # True
The Boolean operators ordered by priority: print(not x and y or x) # True
not x → “if x is False, then x, else y”
x and y → “if x is False, then x, else y” ## 2. If condition evaluates to False
x or y → “if x is False, then y, else x” if None or 0 or 0.0 or '' or [] or {} or set():
# None, 0, 0.0, empty strings, or empty
These comparison operators evaluate to True: # container types are evaluated to False
1 < 2 and 0 <= 1 and 3 > 2 and 2 >=2 and
print("Dead code") # Not reached
1 == 1 and 1 != 0 # True
De scription Example
Adding Add e le me nts to a list with (i) appe nd, (ii) [ 1, 2, 2] . a ppe nd( 4) # [ 1, 2, 2, 4]
e le me nts inse rt, or (iii) list concate nation. [ 1, 2, 4] . i ns e r t ( 2, 2) # [ 1, 2, 2, 4]
The appe nd ope ration is ve ry fast. [ 1, 2, 2] + [ 4] # [ 1, 2, 2, 4]
Inde xing Finds the first occure nce of an e le me nt in [ 2, 2, 4] . i nde x( 2) # i nde x of e l e me nt 4 i s " 0"
the list & re turns its inde x. Can be slow as [ 2, 2, 4] . i nde x( 2, 1) # i nde x of e l e me nt 2 a f t e r pos 1 i s " 1"
the whole list is trave rse d.
Se t A se t is an unorde re d colle ction of ba s ke t = {' a ppl e ' , ' e ggs ' , ' ba na na ' , ' or a nge ' }
e le me nts. Each can e xist only once . s a me = s e t ( [ ' a ppl e ' , ' e ggs ' , ' ba na na ' , ' or a nge ' ] )
Dictionary The dictionary is a use ful data structure for c a l or i e s = {' a ppl e ' : 52, ' ba na na ' : 89, ' c hoc o' : 546}
storing (ke y, value ) pairs.
Re ading and Re ad and write e le me nts by spe cifying the pr i nt ( c a l or i e s [ ' a ppl e ' ] < c a l or i e s [ ' c hoc o' ] ) # Tr ue
writing ke y within the bracke ts. Use the ke ys() and c a l or i e s [ ' c a ppu' ] = 74
e le me nts value s() functions to acce ss all ke ys and pr i nt ( c a l or i e s [ ' ba na na ' ] < c a l or i e s [ ' c a ppu' ] ) # Fa l s e
value s of the dictionary. pr i nt ( ' a ppl e ' i nc a l or i e s . ke ys ( ) ) # Tr ue
pr i nt ( 52 i nc a l or i e s . va l ue s ( ) ) # Tr ue
Me mbe rship Che ck with the ‘in’ ke yword whe the r the ba s ke t = {' a ppl e ' , ' e ggs ' , ' ba na na ' , ' or a nge ' }
ope rator se t, list, or dictionary contains an e le me nt. pr i nt ( ' e ggs ' i nba s ke t } # Tr ue
Se t containme nt is faste r than list pr i nt ( ' mus hr oom' i nba s ke t } # Fa l s e
containme nt.
A ma p( f unc , i t e r ) Exe cute s the function on all e le me nts of l i s t ( ma p( l a mbda x: x[ 0] , [ ' r e d' , [ ' r ' , ' g' , ' b' ]
D the ite rable ' gr e e n' , ' bl ue ' ] ) )
V
A ma p( f unc , i 1, . . . , Exe cute s the function on all k e le me nts of l i s t ( ma p( l a mbda x, y: s t r ( x) + ' ' + [ ' 0 a ppl e s ' , ' 2
i k) the k ite rable s y + ' s ' , [ 0, 2, 2] , [ ' a ppl e ' , or a nge s ' , ' 2
N
C ' or a nge ' , ' ba na na ' ] ) ) ba na na s ' ]
E
s t r i ng. j oi n( i t e r ) Concate nate s ite rable e le me nts ' ma r r i e s ' . j oi n( l i s t ( [ ' Al i c e ' , ' Al i c e ma r r i e s Bob'
D se parate d by s t r i ng ' Bob' ] ) )
F f i l t e r ( f unc , Filte rs out e le me nts in ite rable for which l i s t ( f i l t e r ( l a mbda x: Tr ue i f x> 17 [ 18]
U i t e r a bl e ) function re turns False (or 0 ) e l s e Fa l s e , [ 1, 15, 17, 18] ) )
N
C s t r i ng. s t r i p( ) Re move s le ading and trailing pr i nt ( " \ n \ t 42 \ t " . s t r i p( ) ) 42
T white space s of string
I
O s or t e d( i t e r ) Sorts ite rable in asce nding orde r s or t e d( [ 8, 3, 2, 42, 5] ) [ 2, 3, 5, 8, 42]
N
s or t e d( i t e r , Sorts according to the ke y function in s or t e d( [ 8, 3, 2, 42, 5] , ke y=l a mbda [ 42, 2, 3, 5, 8]
S
ke y=ke y) asce nding orde r x: 0 i f x== 42 e l s e x)
z i p( i 1, i 2, . . . ) Groups the i-th e le me nts of ite rators i1, i2, l i s t ( z i p( [ ' Al i c e ' , ' Anna ' ] , [ ' Bob' , [ ( ' Al i c e ' , ' Bob' ) ,
…toge the r ' J on' , ' Fr a nk' ] ) ) ( ' Anna ' , ' J on' ) ]
Unzip Equal to: 1) unpack the zippe d list, 2) zip l i s t ( z i p( *[ ( ' Al i c e ' , ' Bob' ) , [ ( ' Al i c e ' , ' Anna ' ) ,
the re sult ( ' Anna ' , ' J on' ) ] ( ' Bob' , ' J on' ) ]
e nume r a t e ( i t e r ) Assigns a counte r value to e ach e le me nt l i s t ( e nume r a t e ( [ ' Al i c e ' , ' Bob' , [ ( 0, ' Al i c e ' ) , ( 1,
of the ite rable ' J on' ] ) ) ' Bob' ) , ( 2, ' J on' ) ]
T python -m http.se rve r Share file s be twe e n PC and phone ? Run command in PC’s she ll. <P> is any port numbe r 0 –65535. Type < IP addre ss of
R <P> PC>:<P> in the phone ’s browse r. You can now browse the file s in the PC dire ctory.
I
C Re ad comic i mpor t a nt i gr a vi t y Ope n the comic se rie s xkcd in your we b browse r
K
S
Ze n of Python i mpor t t hi s ' . . . Be a ut i f ul i s be t t e r t ha n ugl y. Expl i c i t i s . . . '
Swapping numbe rs Swapping variable s is a bre e ze in Python. a , b = ' J a ne ' , ' Al i c e ' a = ' Al i c e '
No offe nse , Java! a , b = b, a b = ' J a ne '
Me rge two dictionarie s Use unpacking to me rge two dictionarie s x={' Al i c e ' : 18} z = {' Al i c e ' : 18,
into a single one y={' Bob' : 27, ' Ann' : 22} ' Bob' : 27, ' Ann' : 22}
z = {**x, **y}
Check if two def is_anagram(s1, s2): Find max l = [4, 3, 6, 3, 4, 888, 1, -11, 22, 3]
strings are return set(s1) == set(s2) and min in print(max(l)) # 888
anagrams print(is_anagram("elvis", "lives")) # True unsorted list print(min(l)) # -11
a . ndi m The ndim attribute is e qual to the le ngth of the shape tuple . pr i nt ( np. ndi m( a ) ) # 2
* The aste risk (star) ope rator pe rforms the Hadamard product, a = np. a r r a y( [ [ 2, 0] , [ 0, 2] ] )
i.e ., multiplie s two matrice s with e qual shape e le me nt-wise . b = np. a r r a y( [ [ 1, 1] , [ 1, 1] ] )
pr i nt ( a *b) # [ [ 2 0] [ 0 2] ]
np. ma t mul ( a , b) , a @b The standard matrix multiplication ope rator. Equivale nt to the pr i nt ( np. ma t mul ( a , b) )
@ ope rator. # [ [ 2 2] [ 2 2] ]
np. a r a nge ( [ s t a r t , ] s t op, Cre ate s a ne w 1D numpy array with e ve nly space d value s pr i nt ( np. a r a nge ( 0, 10, 2) )
[ s t e p, ] ) # [ 0 2 4 6 8]
np. l i ns pa c e ( s t a r t , s t op, Cre ate s a ne w 1D numpy array with e ve nly spre ad e le me nts pr i nt ( np. l i ns pa c e ( 0, 10, 3) )
num=50) within the give n inte rval # [ 0. 5. 10. ]
np. a ve r a ge ( a ) Ave rage s ove r all the value s in the numpy array a = np. a r r a y( [ [ 2, 0] , [ 0, 2] ] )
pr i nt ( np. a ve r a ge ( a ) ) # 1. 0
<s l i c e > = <va l > Re place the <slice > as se le cte d by the slicing ope rator with a = np. a r r a y( [ 0, 1, 0, 0, 0] )
the value <val>. a [ : : 2] = 2
pr i nt ( a ) # [ 2 1 2 0 2]
np. di f f ( a ) Calculate s the diffe re nce be twe e n subse que nt value s in f i bs = np. a r r a y( [ 0, 1, 1, 2, 3, 5] )
NumPy array a pr i nt ( np. di f f ( f i bs , n=1) )
# [ 1 0 1 1 2]
np. c ums um( a ) Calculate s the cumulative sum of the e le me nts in NumPy pr i nt ( np. c ums um( np. a r a nge ( 5) ) )
array a. # [ 0 1 3 6 10]
np. s or t ( a ) Cre ate s a ne w NumPy array with the value s from a a = np. a r r a y( [ 10, 3, 7, 1, 0] )
(asce nding). pr i nt ( np. s or t ( a ) )
# [ 0 1 3 7 10]
np. a r gs or t ( a ) Re turns the indice s of a NumPy array so that the inde xe d a = np. a r r a y( [ 10, 3, 7, 1, 0] )
value s would be sorte d. pr i nt ( np. a r gs or t ( a ) )
# [ 4 3 1 2 0]
np. a r gma x( a ) Re turns the inde x of the e le me nt with maximal value in the a = np. a r r a y( [ 10, 3, 7, 1, 0] )
NumPy array a. pr i nt ( np. a r gma x( a ) ) # 0
np. nonz e r o( a ) Re turns the indice s of the nonze ro e le me nts in NumPy array a = np. a r r a y( [ 10, 3, 7, 1, 0] )
a. pr i nt ( np. nonz e r o( a ) ) # [ 0 1 2 3]
Class A blue print to cre ate obje cts. It de fine s the data (attribute s) and functionality c l as s Dog:
(me thods) of the obje cts. You can acce ss both attribute s and me thods via
the dot notation. # c l as s at t r i but e
i s _hai r y = Tr ue
Obje ct A pie ce of e ncapsulate d data with functionality in your Python program that
(=instance ) is built according to a class de finition. Ofte n, an obje ct corre sponds to a # c ons t r uc t or
de f __i ni t __( s e l f , name ) :
thing in the re al world. An e xample is the obje ct "Obama" that is cre ate d
# i ns t anc e at t r i but e
according to the class de finition "Pe rson". An obje ct consists of an arbitrary
s e l f . name = name
numbe r of attribute s and me thods, e ncapsulate d within a single unit.
# me t hod
Instantiation The proce ss of cre ating an obje ctof a class. This is done with the
de f bar k( s e l f ) :
constructor me thod __init__(se lf, …). pr i nt ( "Wuf f ")
Me thod A subs et of the over al l func t iona l ity of an obje ct. The me thod is de fine d
similarly to a function (using the ke yword "de f") in the classde f ini tion. An be l l o = Dog( "be l l o")
obje ct can have an arbitrary numbe r of me thods. par i s = Dog( "par i s ")
Se lf The first argume nt whe n de fining any me thod is always the s e l f argume nt. pr i nt ( be l l o. name )
"be l l o"
This argume nt spe cifie s the instance on which you call the me thod.
s e l f give s the Python inte rpre te r the information about the concre te pr i nt ( par i s . name )
"par i s "
instance . To de fine a me thod, you use s e l f to modify the instance
attribute s. But to call an instance me thod, you do not ne e d to spe cify s e l f .
c l as s Cat :
Encapsulation Binding toge the r data and functionality that manipulate s the data.
# me t hod ov e r l oadi ng
Attribute A variable de fine d for a class (class attribute ) or for an obje ct (instance attribute ). You de f mi au( s e l f , t i me s =1) :
use attribute s to package data into e nclose d units (class or instance ). pr i nt ( "mi au "* t i me s )
Class (=class variable , static variable , static attribute ) A variable that is cre ate d f i f i = Cat ( )
attribute statically in the classde f ini tion and tha t is sha r ed by al l cl as s obje cts.
f i f i . mi au( )
Instance A variable that holds data that be longs only to a single instance . Othe r instance s do "mi au "
attribute not share this variable (in contrast to class attribute s). In most case s, you cre ate an
(=instance instance attribute x in the constructor whe n cre ating the instance itse lf using the se lf f i f i . mi au( 5)
variable ) "mi au mi au mi au mi au mi au "
ke ywords (e .g. se lf.x = <val>).
# Dy nami c at t r i but e
f i f i . l i ke s = "mi c e "
Dynamic An instance attribute tha t is de f ine d dyna mi cal ly dur ing the exec ut ion of the pr ogr am
pr i nt ( f i f i . l i ke s )
attribute and that is not de fine d within any me thod. For e xample , you can simply add a ne w "mi c e "
attribute ne e wto any obje cto by cal ling o. ne e w = <va l >.
# I nhe r i t anc e
Me thod You may want to de fine a me thod in a way so that the re are multiple options c l as s Pe r s i an_Cat ( Cat ) :
ove rloading to call it. For e xample for class X, you de fine a me thodf(...) tha t can be cal led c l as s i f i c at i on = "Pe r s i an"
in thre e ways: f(a), f(a,b), or f(a,b,c). To this e nd, you can de fine the me thod
mi mi = Pe r s i an_Cat ( )
with de fault parame te rs (e .g. f(a, b=None , c=None ).
pr i nt ( mi mi . mi au( 3) )
"mi au mi au mi au "
Inhe ritance ClassA can inhe r it cer tai n cha r act er ist ics (like attribute sor me thods) from class B.
For e xample , the class "Dog" may inhe rit the attribute "numbe r_of_le gs" from the
class "Animal". In this case , you would de fine the inhe rite d class "Dog" as follows: pr i nt ( mi mi . c l as s i f i c at i on)
"class Dog(Animal): ..."
Artist
Logic skills
Logic skills
Decision boundary
Decision
boundaries
## One-liner
svm = svm.SVC().fitX
( [:,:-1], X[:,-1]) ## Result & puzzle
student_0 =svm.predict ([[3, 3, 6]])
print(student_0)
## Result & puzzle # ['art']
student_0 =svmpredict
. ([[3, 3, 6]])
print(student_0 ) student_1 =svm.predict([[8, 1, 1]])
print(student_1)
## ['computerscience']
student_1 .
=svmpredict ([[8, 1, 1]])
print(student_1)
l s t . i nde x ( x ) Re turns the pos ition (inde x) of the firs t >>> l s t = [ " Al i c e " , 4 2 , " Bo b " , 9 9 ]
occurre nce of va lue xin the list l s t . >>> l s t . i n d e x ( " Al i c e " )
0
>>> l s t . i n d e x ( 9 9 , 1 , 3 )
Va l u e Er r o r : 9 9 i s n o t i n l i s t
l s t . r e mov e ( x ) Re move s a nd re turns the firs t occurre nce >>> l s t = [ 1, 2, 99, 4, 99]
of e le me nt xin the list l s t . >>> l s t . r e mo v e ( 9 9 )
>>> l st
[ 1, 2, 4, 99]
List Stores a sequence of l = [ 1, 2, 2] Dictionary Useful data structure for c a l = { ' a ppl e ' : 52, ' ba na na ' : 89,
elements. Unlike strings, you pr i nt ( l e n( l ) ) # 3 storing (key, value) pairs ' c hoc o' : 546} # c a l or i e s
can modify list objects (they're
Reading Read and write elements by pr i nt ( c a l [ ' a ppl e ' ] < c a l [ ' c hoc o' ] )
mutable).
and specifying the key within the # Tr u e
Adding Add elements to a list with (i) [ 1, 2] . a ppe nd( 4) # [ 1, 2, 4] writing brackets. Use the ke y s ( ) c a l [ ' c a ppu' ] = 74
elements append, (ii) insert, or (iii) list [ 1, 4] . i ns e r t ( 1, 9) # [ 1, 9, 4] elements and v a l ue s ( ) functions to pr i nt ( c a l [ ' ba na na ' ] < c a l [ ' c a ppu' ] )
concatenation. [ 1, 2] + [ 4] # [ 1, 2, 4] access all keys and values of # Fa l s e
the dictionary
p r i n t ( ' a p p l e ' i n c a l . k e y s ( ) ) # Tr u e
Removal Slow for lists [ 1 , 2 , 2 , 4 ] . r e mo v e ( 1 ) # [ 2 , 2 , 4 ]
pr i nt ( 52 i n c a l . va l ue s ( ) ) # Tr u e
Reversing Reverses list order [ 1, 2, 3] . r e ve r s e ( ) # [ 3, 2, 1]
Dictionary You can access the (key, f o r k , v i n c a l . i t e ms ( ) :
Sorting Sorts list using fast Timsort [ 2, 4, 2] . s or t ( ) # [ 2, 2, 4] Iteration value) pairs of a dictionary pr i nt ( k) i f v > 500 e l s e ' '
with the i t e ms ( ) method. # ' c hoc o'
Indexing Finds the first occurrence of [ 2, 2, 4] . i nde x( 2)
an element & returns index. # i nde x of i t em 2 i s 0 Member- Check with the i n keyword if b a s k e t = { ' a p p l e ' , ' e g g s ' ,
Slow worst case for whole list [ 2, 2, 4] . i nde x( 2, 1) ship set, list, or dictionary contains ' ba na na ' , ' or a nge ' }
traversal. # i nde x of i t e m 2 a f t e r pos 1 i s 1 operator an element. Set membership pr i nt ( ' e ggs ' i n ba s ke t ) # Tr u e
is faster than list membership. p r i n t ( ' mu s h r o o m' i n b a s k e t ) # Fa l s e
Stack Use Python lists via the list st ack = [ 3]
operations append() and pop() s t a c k. a ppe nd( 42) # [ 3, 42] List & set List comprehension is the l = [ ' h i ' + x f o r x i n [ ' Al i c e ' ,
st a c k. pop( ) # 42 ( s t a c k: [ 3] ) comprehe concise Python way to create ' Bo b ' , ' Pe t e ' ] ]
st a c k. pop( ) # 3 ( s t a c k: [ ] ) nsion lists. Use brackets plus an # [ ' Hi Al i c e ' , ' Hi Bo b ' , ' Hi Pe t e ' ]
expression, followed by a for
Set An unordered collection of ba s ke t = {' a ppl e ' , ' e ggs ' , clause. Close with zero or l 2 = [ x * y f or x i n r a nge ( 3) f or y
unique elements (at-most- ' ba na na ' , ' or a nge ' } more for or if clauses. i n r a n g e ( 3 ) i f x >y ] # [ 0 , 0 , 2 ]
once) → fast membership O(1) s a me = s e t ( [ ' a p p l e ' , ' e ggs ' , Set comprehension works
s qua r e s = { x**2 f or x i n [ 0, 2, 4]
' ba na na ' , ' or a nge ' ] ) similar to list comprehension.
i f x < 4 } # {0, 4}