100% found this document useful (1 vote)
54 views

Python 1

This Python cheat sheet provides descriptions and examples of common Python functions and tricks for working with lists, strings, and other data types. It includes functions for mapping, filtering, sorting, joining, reversing strings, finding duplicates, intersections, and more. It also provides examples of unpacking arguments and dictionaries as well as 14 interview questions covering topics like checking for anagrams, removing duplicates, finding pairs with a given sum, and computing Fibonacci numbers.

Uploaded by

walidderbel1981
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
54 views

Python 1

This Python cheat sheet provides descriptions and examples of common Python functions and tricks for working with lists, strings, and other data types. It includes functions for mapping, filtering, sorting, joining, reversing strings, finding duplicates, intersections, and more. It also provides examples of unpacking arguments and dictionaries as well as 14 interview questions covering topics like checking for anagrams, removing duplicates, finding pairs with a given sum, and computing Fibonacci numbers.

Uploaded by

walidderbel1981
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Python Cheat Sheet - Functions and Tricks

"A puzzle a day to leorn, code, and play" ... Visit finxter,com

Oesc rlptl on Result


, map( f unc , iter) Executes the function on ail ell'ments of l1st {map {hmbda x: x [II ] . [ 'red' , [
., .. 'g' , 'b' ]
the jterable
,o 'green' , 'blue' ] )}

, 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

o sorted(lter) Sorts lIerable in ascendlng D'der sorted( [8 , 3, 2, 4 2, 5 )) [ 2, 3, 5, 8, 42]


,
, sorted(iter,
key .. key)
Sorts !lccordmg to the key hmctlon in
ilscendlng orOer
sorted([ 8 , 3, 2, 42 , 5 ) , key _lambda
x: Il if x-.42 else l()
[42, 2, 3, 5, 8 ]

help(func) Returns documentatlOn of fune he lp [st .. , upper{ ) ) to upp"rcas" , '

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"

Use unpacklng for multiple asslgnment


feBlu,e on Python
f { " { ' z' : 4 , 'x' : 1 , y ' 3})

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

Quesllon 000. QlHI5tlon Code

Ch"ck If Ilsl 1 ~ [ l , l, 4, 5, 2, 111, 5] Gel m'salng def let __ lsslnLn_r (l,t);


contalns print( l ll ln 1 ) • Tru~ number ln r etur. set(r. n g~(lst[len(lst) - l ])[ l :)) - 'et(l)
Inlege, x [1 ... 100] 1 _ Iht(r3n8"( l , l9Q ))
1 . '...., • • ( 58 )
prlnt (let_. I •• l n ,-nu~ber( I ») • se
Flnd dupllcal"
numbe, ln
def f in d_duplic . tes (eleae nt s):
dupllcates, seen _ . et (), set () ,,.
Compute def Intersect (htl, hU):
res, hU _cop~ _ [], I.U[:]
Inlege,lIs l f or el..ent ln el~nts: Inl.rH<:tlon f or el ln IHl:
I f ~I..ent ln , een : of IWo IIs ts i f el ln 1 ,t2_ <op~:
dupl lcate< . add(el..ent ) r"s . append(d)
seen.add(el..ent ) Ist 2_copy. re.ov.( el)
return li.t (d uplic.t es) return res

Check Il IWO def 1._.n.,r~ (sl,s2}: Flnd mu 1 _ [4, l, 6 , l, 4 , 888 , 1, - U , n, l]


"rlngs ar. re t urn ,et ('l) __ .e t {'2) a nd min ln print ( ... (I» .
688
anag,ams print {i,_analram{ "elvi," , -live," ) • True uns orted IIst print(_in(I) .·l1

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]

• le, 1, 2, 3, 4, 5, 6, 1, 8, 9] prlnt (revene( " " oll o") • olleh

Flnd pal's 0 1 dd findJl&lr« I, x ): Comput. a,b . 8, l


Inlegers ln lit! p~lrs _ [ ] !ha n...! n n _ 10
8 0 Ihal Ihelr f or (l, el_l) in en..-ran(l): Fibonacci f or 1 in r ange (n):
' um Is equal 10 f or (j, el_2) ln en..erate(l[1.1 :j): numbert prlnt(b)
Inlege, x If el_l • el_2 __ . : a,b _ b , a~ b

pal,..append«el_ l, el_2» • 1, 1, 2, 3, S, 8,
rdurn pain

Check Il a def l<-POllndra.. (phrase )' Sort Ils! wlth dd q,oM: ( l ) :


"rlng 1. e re t urn phr.s e __ phr. se [::- l ] Qu lck60rt if 1 __ (]: ret urn (]
palindrome prlnt (i'Jlallndrono( "ann ."» • True . Igorithm return q.ort ([ . f or x i n l[ l :J if X< l[ e ]]) • l[ e : l ] •
q.ort ([. f or X ln L[ l : J If . '- L[ 8JJ)
Ist ~ [44 , 33, 22 , 5 , 77 , 55, 999 J
prlnt(~sort(lst»

" [5, n, 33, 44, 55 , 71, 999J

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

A contai ner data type tha t stores a 1 - [1, 2, 2]


sequence of e leme nts. Unl ike s trings,lists print(len(l)) Il 3
are mutable: modirtCatlon possible

Add elements to a list with mappend, Oi) l' , 2] .append[4 ) /1 l', 2, 4 ]


Adding
elements ln5ert, or (iiî) Ils! concatenatIon. "
", " 4 ) .inse r t ( 2, 2) Il [l, " 2, 4]
The append operat ion Is very fast.
", " 2]+ [4 )#[1, 2, 4] "
"
Remova l Removlng an elemen t carl be slower.
", "" 4 ) .remove ( 1) Il ," " '1
l' , 3]. reverse() # [3, ,1
R<lverslng This reverses the order of list elements.
" "
Sortlng Sorts a Ils!. The computatlonal comp lexlty
of sortlng is Ojn log ri) for ri list elements.
," " 2] .sort {) Il \2,
" '1
Indexing Finds the first occurence of an elemen t in [ 2, 2, 4 ]. inde ~ ( 2 ) # index of element 4 15 He"
the list & retums Ils Index. Can be slow as [2, 2, 4 ) .index (2, 1) Il index of element 2 afte r rms 1 is "1"
the whole IIst 15 traversed,

Stack Python IIsts can be used Intuitively as stack stac k - (3)


via the two IIst operatIons appendQ and stack.append (42 ) Il [3. 42)
popo stac k. rmp() /1 42 (sta ck: [3])
stad:.rmp{) Il 3 (stad: [ l)

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

Method Description Example

lst . append(x) Appends el ement x ta the IIst l:l t. .> 1 - [1


.> l " ppendI421
1 . apl>"ndI2:1
[~2 . 21

l st.clear() Removes ail elements Irom the list » > IH


",
. . •• "

1.t . clu'U
,,.
;
• ;

Ist- which becomes empty.


" ,.
lst .copy O Retums a copy 0 1 the list Ist. Copies only
the lis!. notthe elements in the list (shallow
" '"' -
", 1." . ~opy [1
;

copy). '. "


lst .count(x) Counts the number 0 1 occurre nces of
»>
.t-
.>
ht . co~n t [")
element x in the list Ist.
;

,
>>> h t . coun t. /21

lst . extend(iter) Adds a il elements 0 1 an iterable ital' (e.g. .> lst ~ . • z. ,.


another list)tothelist lst. »> 1", . ~x,~,· , , (·4 . 5 . 6'1
1. :> . >. ' . _o . r.l

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

>>> lst.ic.de x [99 , :, li


Va~ueEccoc : 99 i . ne t. ~n l ~ s t.

lst.insert(i, x ) Inserts element x al position (inde x) i in ., ,,, ,.


'. .. " ;

,. ,. ,. ., '"
ht.LuH(l .
",
the list lst.
1: •

lst .pop() Removes and retums the final element of > > , ,.
• ;

the list Ist.


., '"ht .!w p ll
>
» ,oc
", "
l st. remove (x) Re moves and retums the lirst occurrence ", ,,, • ,. , n. ,, 91 ;
I n . " .. mov .. "(99 1

.
",
of element x in the list ls t.

", ,'", , '"


",

lst . reVerSe () Reverses the arder 01 elements in the list he - ? ' . 41


l" . ~"Ye~ ~ ,,\ 1
Ist .
» I~ 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" )

Method A subset of the overal l lunctlonality of an object The melhod Is defined


slmilarly 10 a lunction (uslng the keyword "der) ln the class definition. An bello • Doe( "bollo" )
obJec t can have an arbitrary number 01 methods. pads • DoII( "pods" )

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

pri" t (p~ris . n ... )


se l f glves the Python Interpreter the Information about the concrete
"pad."
Inslam:e. To define a method, you use self to modlly the Instance
a!lributes. But to coll an Instance method, you do not need ta specily se l f
clau en ,
Encapsulation Bind in g loge!her dllta and lunCllonalrtv thm manipulmes !he data.

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

Keyword Des cri ption Code e xample

fa Ise , True Data values from the data type Boolean fa Ise __ ( 1 > 2), True ._ ( 2 > 1)

and , or , not Logica l operators: x, y _ True , False


(x and y) .. both X and y must be True ( x or y) .. _ True # True
( x or y) .. elther x or y must be True ( x and y) __ false /1 True
( not x) .. x must be fa lse ( not y ) _. True # True

b.. e~~ Ends loop prematurely while ( True ) :


break /1 no infinite loop
print( "hello "orld" )

c ont1nu~ Flnlshes current loop Iteration while ( True ) :


continue
print( "43" ) ~ d e ~d code

cl ass Defines CI new clClSS .. CI real -world cOr"lcept class Be er :


(object orlenled programmlng) def _ init_(self) :
sel f . content .. I.e
Defines a new functlen or class method. For latter. def dr in k(se lf ) :
'" firs! parame!er ("se lf') points 10 the c:lass obJect. self. content _ e.e
When call1ng çlass melhod. firsl parame!er Is Implicit.
bec ks _ Beer() /1 constructor - (reate class
becks. drink () # beer empty: b.content .... Il

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

1 Checks whether elemenl 15 in sequence 42 in [ 2, 39 , 42 } jj True

Checks whether bath elements point ta the same y _ x _ 3


abject x is y # True
[ 3] is p ] # False

.m. Empty value constant


.-,
def f C) :

f() is None # True

Ia ..bda Function wi!h no name (anonymous functJon) ( lillllbda x: x + 3)(3) jj returns 6

Terminales exe<:ution of the function and passes the de f incrementor ( x) :


flow of exe<:utlon 10 Ihe caller. An optional value after ret urn x + 1
the return keyword specifies the function resu lt Incrementor( 4 ) /1 retyrns 5

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

def COIIIII1and (s elf , x ) :


""'"" . ' AJi<r' """", . -- ' i f x .... self . name :
SUIte * ' .leepirlg· .!Me - "wag t.U·
<DIor • 'g<ey'" <olof • 'bIIIc ~ '
seH.ba rk(2)
~ l1 f x .... "s1t" :

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!

prin t (employee.fi r stname + " " be llo.specte s .... [ "wH" ]


.. employe e .liIstn ame .. " " prtnt ( l ent be 110. spee l e s)
.. str(employee.sahry ) + "SM ) •• len( a lic e .spe ci es» # True (1)
# alic e wonde r land 1221100S

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

<s11ce> • <val> a • np.array( [ 9 , l , 9 , 9 , 9 ])


Rep lace the <sllce" as selected by the sllcing Ope,aw, wlth
the value <v~I>. a[:: 2 1 • ,
print {a} /1 [2 1 2 9 2)

np .va r(a) Calculmes lhe variance of Il numpy arrsy. a • np.array( [ 2 , ' ])


prlnt(np. var(a}) /1 4.9

np . std(a) OIrculates the standard devlation of 8 numpy prray print (np.std(all /1 2. 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

np,max(a) RelUrns the ma~lmal value 01 NumPy array 8. a .. np.array([ 19, 3, 7 , l , 9 ])


print {np .ma~ (a» n.
np.argmax(a) RelU'OS the Indc~ 01 the clement Wllh maXimal value ln the
NumPy array 8.
a • np.array([ 19, l , 7 , l , 9 ])
print {np.argma~ (a}) ..
np,llOnzero(a) Retulfls the indices of the r>anzero elements in NumPy array a " np. array( [ 19, 3, 7 , l • 9 J )
• print {np.nonzero(a}} /1[9123)

f inxt e r

You might also like