Python 1
Python 1
"A puzzle a day to leorn, code, and play" ... Visit finxter,com
, map ( f unc , il, ... , Executes the lunetlon on ail k element, of l1st (map ( hmbda x, y: st r{x) + • [ 'II appl es' , '2
,
, ", the k ~e,ables y + 's' , [II , 2, 2 ) , [ 'apple' ,
' orange' , 'banana' J)
oranges' , '2
bananas ' ]
,
o string.joln(lter) Concatenates Iterable elements 'marries ' ,join(list([ 'Al1ce' , 'Alice .arries Bob'
separated by string 'Bob' ])
, f llter( f unc, Filters out !!Iements ln I!erable for wh lch l1st (filter( lambda x: True if x >17 [ 18 ]
," iterable ) fuoc~on retum, Fa15e (or 0) el$e False , [ l , 15 , 17, 18])
,
C strins.strip() Removes I"adlng and trillling print( " \n \t 42 \t " ,strip()
, whlte'paces 01 string
lip(U, 12, . .. ) Groups the I-th elements 01 Il,,ra10l5 Il. 12, I l st (z ip ( [ 'AlI ce' , ' AIlna ' l , [ ' Bob' , [( 'AUce' , 'Bob' ),
. together 'Jon' , 'Frank' )) ( 'AIlna' , 'Jon' )]
Equal 10: Il unpack the lipped Ils\, 2) zip l1st {lip{ ' [{ 'Alic e ' , 'Bob' }, [( 'Alice' , 'AIlna' ),
thl:> result ( 'AIlna' , 'Jon' ) ] (' Bob' , 'Jon' )]
enumerate(iter) Assigns Il counter value to each elemenl list (enumerat e { [ ' Alüe' , ' Bob' , [( II , 'Alice' ), (l,
of the iterabie 'Jan' ] » 'Bob' ), ( 2, 'Jan' )]
,, python -.m http.server 5hare files belween PC and phone' Run command ln pc', shl:>ll. <p> 15 IIny port number 0-65535. Type <: IP address of
, <"
p<>:<p;. In the phone', blOwser. You c~n now Drewse the files ln the PC d"cctory.
,,
C Read comle import antigravi t y Open the comlC s.erl~ xkcd ln yeur web browser
Zen of Python lrnport th15 '",Beautiful 15 bette r than ugly, Explidt 15 ...
SwapPlng numbers Swapptng variableS;5 Il breeze in Python. a , b • 'Jane' , 'Alice' a _ 'Alice'
NO offense, Javal a, b.b, a b . 'Jane'
Unpackirlg arguments Use a sequence 115 lunehon arguments def f (l( , y, z) : return x + y ' z
via aste,lsk operalo'·. Use il dictlonary f {' [ l , 3 , 4 ]) B
Exlcnded Unpockinll
(key,value)vladouble8stefiskoperator"
a, ' b • [ l , 2, 3, 4 , 5J .. ,
13
b • p, 3 , 4, 5 ]
Merge!Wo d'C\IOnarie, Use unpacklng to merge IWO dlcllonarles h( ' Ali,e' : 18 } z • { 'AU,e' : 18 ,
inlo~slng leone y_{ '80b' : 27 , 'Ann' , 22 ) 'Bob' : 27 , 'Ann' : 22 )
z • {" ~ , " y}
f inxt e r
Python Cheat Sheet: 14 Interview Questions
~A puzzle a day ta learn, code, and play" ..
'FREE' Python Emai l Course @ http:Ubjt.ly/free-pytbon-course
R"mov"aU Ist • Iist(range( 19 )) • list(range( t 9 » R.v . .... def reveru ('trl ng):
dupllcates tram l't _ list(set (lst» strlng us lng if len(.trlnl)< _l : return strinl
IIsl print (l<t) "",u.slon r~ t urn r~v~r< ~ ('lrlng [ l :]) . strl n &[ B]
pal,..append«el_ l, el_2» • 1, 1, 2, 3, S, 8,
rdurn pain
Use lis!.' ••• ,llst ... Flnc! ail d~f Bct Jlc ..... tation. ( w):
lIack, e rr.y, 1 _ [ l,4] JI'Innutation if len( w)' _I ;
and queue l ,_ [ S, 6 ] • 1 _ [3, 4, 5, 6) 4 0ht,ing return '01(")
<•• ller ~ 8et_~rMut.tlon.(w[ 1 :J)
•I .appendas ( ala )<taok
, 1 • [4, 5, 6, le]
pe .... _ SH ()
f or x ln s.a ll er:
J.pop() . 1 . [4, 5, 6] f or PO' ln r.n&e( 0 ,len( x)+1 ):
pe ... - .[:po,] • w[ 8 J •• [po>:]
• ... and a,.
queue ~r., .•
dd(pe ... )
J.lnsert( 9, 5) 1 1 _ [5, 4 , S, 6J return pe ......
J.f'O!'() • 1 • [5, 4, S] prlnt(letft ..... uta tions( " nan" »)
• ('nn. · , ·.nn', · n.n·]
f i nx t er
Python Cheat Sheet - Complex Data Types
"A puzzle a day to learn, code, and play" .. Visit finxter,com
Description E~ample
5., A set Is an unordered collectJon of basket _ ( ' apple' , ' eggs' , 'banana ' , ' orange' )
e lements. Each Clin e~ isl only once. same - set ( [ ' il pple ' , ' eggs' , ' bilnilnil' , 'orilnge ' )
Dlctlo nary The dlctlonary Is a useful data structure for calories. { 'ilpple' : 52, ' bilnanil ' : 89, 'c hoco' : 546}
Sloring (key, value) pa irs.
Read ing and Read and wr lte elemenls by speclfying the print( cil lories[ ' apple ' 1 ( cil lories [ ' choco ' ] ) Il True
wrlt ing Key wlth in the brackets. Use the keysQ and calories [ ' (appu ' ] • 74
elements valuesQ functlons 10 access ail keys and print(calories[ 'banana' ] (c a lo r ies[ 'cappu' ] l Il False
values of the dlctionary, print( 'apple' in calorie s. key s(» Il True
print( 52 in calories.valuesO) Il True
Dlctlonary You can loop over the (key, va lue) pairs of for k, v in calories. ite.,s ():
Loopi ng a dlctionarywiththe ItemsQmethod. print(k) if v > 506 else Non e ~ 'chocohte'
Membershl p Check with the 'in' keyv<ord whether the basket . ( ' apple' , ' eggs' , 'bana na' , ' oril nge' )
o pe rator set. list, or dictionary contilins an e lement. print( 'eggs' in bas ket} # True
Set con ta inmen t Is faster than list print{ ',"ush r oooo' in bilsket } # Fil lse
contalnmenl,
List and Set List complehenslon is Ihe concise Python # List comp r ehens i on
Comprehens way to creale lists. Use brackets plus an 1 _ [( 'Hi' + x) for x in [ 'Alice ' , 'Bob' , ' Pet e ' ])
ion expression, followed by a for clause. Close print{l) Il ['Hi Alice ' , ' Hi Bob', ' Hi Pete' ]
with zero or more for or if clauses. 12 • [x • y for x in r ange ( 3) f or y in rilnge ( 3) i f x>y ]
print(12) Il le, e, 2]
Set comp lehenslon Is slml lal \0 list # Set COll1prehension
comprehe nsion. square s . { x·· 2 for x in [e , 2, 4 ] i f x ( 4 ) Il (e, 4)
f inxt e r
Python Cheat Sheet: List Methods
"A puzzle a day to learn, code, and play" ... Visit finxter.com
,
>>> h t . coun t. /21
lst . index (x) Retums the position (index) of the lirst »> lH - _" Al .... .. 4 • • " '. ,1)" , 99)
occurrence 01 value x in the list !st. >>> lat . ;' , ~ ./ " ;o.I.~~ " 1
,. ,. ,. ., '"
ht.LuH(l .
",
the list lst.
1: •
lst .pop() Removes and retums the final element of > > , ,.
• ;
.
",
of element x in the list ls t.
, "
l st.sortO Sorts the elements in the lisl ls t in as . '.:" .
>>> hl. - 4 <. H . ")
ascending order. .» hL.onu
, :, . 'l , :, . q . 881
.> ht . . Htl k prld-,bôd x : "U!xl 10'1
! Il. 12 . i . • 881
f inxt e r
Python Cheat Sheet: Object Orientation Terms
"A puzzle a day to learn, code, and play" ... Visit fi nxter,com
Description EJ!ilmple
Class A blueprint ta create obj ects. It defines the data (allributes) and functionality
(methods) of the abjects. You can e(cess both allributes and methods via
the dot notation. /1 cl .... attrlbuh
h_ha1rv • lr"e
Object A plece of encapsula ted data w ith functionality ln your Python program that
(=instance) Is bullt according to a class definition. Often. an object corresponds to il /1 c"".truct<>r
thlng ln the real world. An e~amp l e Is the obJect "Obama" that is created de f _init_(self, n.... ) :
/1 in.tane~ attrib"t~
accordlng to the ciass definltlon "Pers.on". An object conslsts of an arbitrary
. ~ lf.na ... . na ...
number of att ributes and methods. encapsulated within a single Unit.
/1 _t""d
Instllntlalion The process of creatlng an abj ect 01 a (Iass . This Is done with the
def b~rk (.elf):
constructor melhod _lnIL(se lf...). print( "W\JH" )
Se lf The first argument when defining any methOd Is always the sel f argument. prlnt(bello.na.. )
"bollo"
This argument specifies the Instance on whlch you ca li the melhod
Attribu te A ~ariable def.ned for a class (cillss attrlbutel or lor an obJect Onslance attrlbute) You
/1 _t""'" ov~rLOQd{ng
def .bu(.eH, U ..... l ):
use /I!lnbutes 10 Pl'ck~ge d~l~ inlo enclose<! un~s (class or Instance). pr:lnt( ".:I .. " • t:l... )
Class (=class variable. static variable. static attribute) A l'sriable thm is creDted HH • CatO
attrlbute statically ln the class deflnition and !hat 15 shared by ail cla55 obJeds
fifi..buO
Instance A ~arlable that holds data that OOlongs only to D Single instance. Other Instances do "dau •
attrlbute nOI share thls variable Qn contrasi ta class allributes). In most cases. vou create an
(=instance Instance attribute x ln the cO(J$lroctor when C,eajing the Inslance It5elf using lhe self f1H .• hu( S )
variable) "Riau .iau Riau .iau Ria" "
kcywords (e.g. s('If.~ <val».
Il IIyn.-ic attril><>h
flfI.Uke • • ".:lee"
Dynam ic An Inslance Mtribu le thal is defincd dynamocally dunng the e~ccutlon of the pr09rnm
print(flf1 . 11k ~ s)
attrlbute and that is not defined wlthln any me!hod For example. you can simply IIdd a I">I!W ".iu"
attrib ute neew toBny objed obycalllng o .neew . <va l>
• Inh~rHQn,~
Method You mey want to define a method ln a wny so that there Me multip le options d .. s ~ers:lan_Cat {Cn):
overloading 10 caliit. For exampte for class X. you deflne a method fi ...) that can be called clas.ification • "Persiln"
in three ways: f(a), f(a,b), or f(a.b,c). To this end, you can define the method
. :l.i • Persian_'.t()
wlth delaul t parameters (e.g. I(a, b-None, C' None).
print (.iai. Ria"( l »
".hu .hu .hu "
Inheritance Class A can Tnhent certain cha,acteris!lcs (I lke attrtbUles or me!hods) Irom class B.
For example. the class "009" may Inhent the attribute "number _OUeg5" Irom the
class "Animal". In thls case. you would define the Inherited das5 "Dog" as fOllows: prlnt (. Ll1 . classlflcatlGn)
"class DogtAnimalj: •
f i n xt er
Python Cheat Sheet - Keywords
~A puzzle a day ta leorn, code, and play" ... Visit finxter,com
fa Ise , True Data values from the data type Boolean fa Ise __ ( 1 > 2), True ._ ( 2 > 1)
if, elH, else Conditlor'l8 l program executlon: pregram star!s wl!h x .. int(input( "your value: "»
"iF branch. tries the "eliF branches. arld firlishes with H x ) 3 : print( "Big" )
"else" branch (unlil one branch evaluates la Truel. eUf x . - 3 : print( "MediUIII" )
else : print( "5.... 11- )
f or, "hile # for loop declaration # While loop • Same sua ntics
f or i in [1I , 1 , 2 J : j - ,
print(i) while j < 3 :
print(j)
j - j + 1
fi n x t e r
Python Cheat Sheet - Classes
"A puzzle cr day to learn, code, and play" .. Visit finxter,com
[)es<:ription Example
Classes A das;; encapsu lates data and functJonal ity· data as c la ss Dog :
•• • Blueprint of a dog "" "
attribules. ilnd functlonality as melhods. Il i5 a bluepr int
to create concrete Instances in the memory.
# cl ass vari able sha red by a Il insta nces
Class Instances <peei e s .. [ " canis lupus" ]
..
Anributn
def ~init_(self , name, color) :
self.name .. name
~-
stote . ;t-,".• .elf . st ate .. "sleeping"
, olof .. ... ,
self . color .. color
•
Instance You are an Instance of the class human. An instance is il self.state .. "sit"
concrele implementation of 11 das;;: ai l aUricules of an ehe :
Instance h,wE! a flxed "alue. You. hait i5 blond. brown, or se lf. s t ate .. "wag tail"
black - but neller unspeclfled.
de f bar k(self , freq) :
Each instance has Ils own altributes independent of f or 1 l n range(freq):
other Instances. Yet, class varIables are ditferen!. These prln t ( "[" + se lf. naroe
arE' data values ilssociated w ith the class. not the .. Ml : IoIoofl" )
Instances. Hence, ail Instance share the same class
variab le spec ie s in the example_
bello .. Oog( "bello" , " black" )
Se lf The tirst argument when deti ning any method is aiways allce .. Dog( " all ce" , "will te" )
the self argument_ This argument speclfles the
prtnt(be llo.eolo r ) • black
instance on whlch you cali the method_
prlnt( a llce.color) # white
se l f glves the Python Inl erpreler the Information about
theconcrelelnstanceTodefineamethod.youl.lse sel f bello.bark( l ) # [bello] : i>Ioof!
10 modify the Instance altrlbules_ Bu t to coll an Inslance
melhod. you do nol need to spedfy se l f a l tee. eom and( "51 t" )
print( " [aH ce ] : " .. aHce.s t ate)
Creat ion You can c reate Classes "on Ihe fly" and use Ihem as # Calice ] : ,it
I09lcal unllS to store comple~ dala types.
be llo.com and( "no" )
c la ss Employee() : prtnt( "[ bello ] : " .. bello., t ilte)
pa« # [bello]: wilg t all
employee .. rmployee O
employee .sa la r y .. 121000 a l tc e . comand( "al te e " )
employee.firstname .. Malice" # [alice ] : WoofJ
employee. la st nilme .. "wonde r liInd" • Calice] : Woof!
f i n xt er
Python Cheat Sheet: NumPy
"A puzzle a day to leorn, code, and play" .. Visit finxter,com
Nam. De sc ription bampl.
a.shape The shape anfibule 01 NumPy .may a keeps il tuple of III).arra)'([[ 1, 2],[ 1, 1],[0, 0]])
il ..
Integers. Each Intage, descriOeS the numoor o f elements of print (np.shape(a» /1 (3, 2)
the IIxls.
a . ndill The n<jim attrlbute is equal 10 the length of the shupe tuple. print {np.ndim{a})
The ilste';sk (star) operillor peffornrs Ihe H!!damard product, il" np.array( [[ 2, e l. [ O, 2 1l)
l,l' .. multipl ies two matriCes will! equ.a l shape eleJTl<>nt-wise. b .. np.array( [[ l , I l , [ 1, I l])
pr1nt(a *b) /1 [[2 9J (6 2])
np .matmul(a,b) , a@b The standard matrlx multiplicabon ope,ator . EquNaient to the print (np. ma t mul (a, b) )
<Ioperator. /1 ({2 2) (22)}
np . arange([start, lstop, ereates a new 10 numpy array Wlth evenly spaŒd values print (np.arange( 9 , 19, 2})
[step, ]) /1(62468J
np . l1nspace(start, stop, ereates il new 10 numpy arr~y Wlth evenly spreBd element~ print {np.linspace( 9 , 19, 3)
num_S0 ) Wlthln the grœn Intetyai /1 r
6. 5. 16.J
np . averilge(a) Averages over ai l the value~ ln the numpy 8rray a • np.array([[2 , 9 1, [ 9 , I l])
print(np.average(a» /1 1.6
np.di ff (a) CIIlculates the dlfference be!Ween subsequent values ln fibs • np.array([ 9 , 1, 1, 2 , 3, 5 ])
NumPy array 8 print (np.diff(fibs, no l »
/I(19112J
np . curnsum(a) Calculates the cumulmNe sum of the elements ln NumPy print(np.cu~su~(np.arange( 5 1)1
arr8ya. 1/ (9 1 3 6 19J
np,sort(a) Creates 8 new NumPy array wlth the values from a a • np.array([19, 3, 7 , l , 9 11
(ascending). print (np. sort (a»)
1/ (6 l 3 7 l6)
np.argsort(a) Returns the indices of il NumPy array so tha! the indexed a • np.array([ 19, 3, 7 , 1, 9 ])
values would be sorte<:!. print (np. argsort (al)
1/(43129J
f inxt e r