You are on page 1of 11

Python Cheat Sheet - Keywords

Keyword Description Code example

False, True Data values from the data type False == (1 > 2), True == (2 > 1)

and, or, Boolean Logical operators: x, y = True, False


(x and y) → both x and y must be True (x or y) == True # True
not
(x or y) → either x or y must be True (x and y) == False # True
(not x) → x must be false (not y) == True # True

break Ends loop prematurely while(True):


break # no infinite loop
print("hello world")

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

x = int(input("your value: "))


if, elif, else Conditional program execution: program starts with if x > 3: print("Big")
“if” branch, tries the “elif” branches, and finishes with elif x == 3: print("Medium")
“else” branch (until one branch evaluates to True). else: print("Small")

# While loop - same semantics


j = 0
for, while # For loop declaration
while j < 3:
for i in [0,1,2]:
print(j)
print(i)
j = j + 1

42 in [2, 39, 42] # True

in Checks whether element is in sequence y = x = 3


x is y # True
Checks whether both elements point to the same [3] is [3] # False

is object
def f():
x = 2
None Empty value constant f() is None # True

(lambda x: x + 3)(3) # returns 6

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.

(Tap here) Join WhatsApp for more such FREE stuff


Python Cheat Sheet - Basic Data Types
Description Example

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

Integer, An integer is a positive or negative number ## 3. Arithmetic Operations


Float without floating point (e.g. 3). A float is a x, y = 3, 2
positive or negative number with floating point print(x + y) # = 5
precision (e.g. 3.14159265359). print(x - y) # = 1
print(x * y) # = 6
The ‘//’ operator performs integer division. print(x / y) # = 1.5
The result is an integer value that is rounded print(x // y) # = 1
towards the smaller integer number print(x % y) # = 1s
(e.g. 3 // 2 == 1). print(-x) # = -3
print(abs(-x)) # = 3
print(int(3.9)) # = 3
print(float(3)) # = 3.0
print(x ** y) # = 9

## 4. Indexing and Slicing


String Python Strings are sequences of
s = "The youngest pope was 11 years old"
characters.
print(s[0]) # 'T'
The four main ways to create strings are the
following. print(s[1:3]) # 'he'
print(s[-3:-1]) # 'ol'
1. Single quotes print(s[-3:]) # 'old'
'Yes' x = s.split() # creates string array of words
2. Double quotes print(x[-3] + " " + x[-1] + " " + x[2] + "s")
"Yes" # '11 old popes'
3. Triple quotes (multi-line)
"""Yes ## 5. Most Important String Methods
We Can""" y = " This is lazy\t\n "
4. String method print(y.strip()) # Remove Whitespace: 'This is lazy'
str(5) == '5' # True print("DrDre".lower()) # Lowercase: 'drdre'
5. Concatenation print("attention".upper()) # Uppercase: 'ATTENTION'
"Ma" + "hatma" # 'Mahatma' print("smartphone".startswith("smart")) # True
print("smartphone".endswith("phone")) # True
print("another".find("other")) # Match index: 2
These are whitespace characters in strings. print("cheat".replace("ch", "m")) # 'meat'
●Newline \n print(','.join(["F", "B", "I"])) # 'F,B,I'
●Space \s print(len("Rumpelstiltskin")) # String length: 15
●Tab \t print("ear" in "earth") # Contains: True

(Tap here) Join WhatsApp for more such FREE stuff


Python Cheat Sheet - Complex Data Types

De scription Example

List A containe r data type that store s a l = [ 1, 2, 2]


se que nce of e le me nts. Unlike strings, lists pr i nt ( l e n( l ) ) # 3
are mutable : modification possible .

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]

Re moval Re moving an e le me nt can be slowe r. [ 1, 2, 2, 4] . r e move ( 1) # [ 2, 2, 4]

Re ve rsing This re ve rse s the orde r of list e le me nts. [ 1, 2, 3] . r e ve r s e ( ) # [ 3, 2, 1]

Sorting Sorts a list. The computational comple xity [ 2, 4, 2] . s or t ( ) # [ 2, 2, 4]


of sorting is O(n log n) for n list e le me nts.

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.

Stack Python lists can be use d intuitive ly as stack s t a c k = [ 3]


via the two list ope rations appe nd() and s t a c k. a ppe nd( 42) # [ 3, 42]
pop(). s t a c k. pop( ) # 42 ( s t a c k: [ 3] )
s t a c k. pop( ) # 3 ( s t a c k: [ ] )

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

Dictionary You can loop ove r the (ke y, value ) pairs of f or k, v i n c a l or i e s . i t e ms ( ) :


Looping a dictionary with the ite ms() me thod. pr i nt ( k) i f v > 500 e l s e None # ' c hoc ol a t e '

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.

List and Se t List compre he nsion is the concise Python # Li s t c ompr e he ns i on


Compre he ns way to cre ate lists. Use bracke ts plus an l = [ ( ' Hi ' + x) f or x i n[ ' Al i c e ' , ' Bob' , ' Pe t e ' ] ]
ion e xpre ssion, followe d by a for clause . Close pr i nt ( l ) # [ ' Hi Al i c e ' , ' Hi Bob' , ' Hi Pe t e ' ]
with ze ro or more for or if clause s. l 2 = [ x * y f or x i nr a nge ( 3) f or y i nr a nge ( 3) i f x>y]
pr i nt ( l 2) # [ 0, 0, 2]
Se t compre he nsion is similar to list # Se t c ompr e he ns i on
compre he nsion. s qua r e s = { x**2 f or x i n[ 0, 2, 4] i f x < 4} # {0, 4}

(Tap here) Join WhatsApp for more such FREE stuff


Python Cheat Sheet - Classes
Description Example

Classes A class encapsulates data and functionality - data as


class Dog:
attributes, and functionality as methods. It is a blueprint
""" Blueprint of a dog """
to create concrete instances in the memory.
# class variable shared by all instances
species = ["canis lupus"]

def __init__(self, name, color):


self.name = name
self.state = "sleeping"
self.color = color

def command(self, x):


if x == self.name:
self.bark(2)
elif x == "sit":
Instance
You are an instance of the class human. An instance is a self.state = "sit"
concrete implementation of a class: all attributes of an else:
instance have a fixed value. Your hair is blond, brown, or self.state = "wag tail"
black - but never unspecified.
def bark(self, freq):
Each instance has its own attributes independent of for i in range(freq):
other instances. Yet, class variables are different. These
print("[" + self.name
are data values associated with the class, not the
instances. Hence, all instance share the same class + "]: Woof!")
variable species in the example.
bello = Dog("bello", "black")
Self The first argument when defining any method is always
alice = Dog("alice", "white")
the self argument. This argument specifies the
instance on which you call the method. print(bello.color) # black
print(alice.color) # white
self gives the Python interpreter the information about
the concrete instance. To define a method, you use self
bello.bark(1) # [bello]: Woof!
to modify the instance attributes. But to call an instance
method, you do not need to specify self.
alice.command("sit")
You can create classes “on the fly” and use them as print("[alice]: " + alice.state)
Creation
# [alice]: sit
logical units to store complex data types.

class Employee(): bello.command("no")


pass print("[bello]: " + bello.state)
employee = Employee() # [bello]: wag tail
employee.salary = 122000
employee.firstname = "alice" alice.command("alice")
employee.lastname = "wonderland" # [alice]: Woof!
# [alice]: Woof!
print(employee.firstname + " "
+ employee.lastname + " " bello.species += ["wulf"]
+ str(employee.salary) + "$") print(len(bello.species)
# alice wonderland 122000$ == len(alice.species)) # True (!)

(Tap here) Join WhatsApp for more such FREE stuff


Python Cheat Sheet - Functions and Tricks
“A puzzle a day to learn, code, and play”

De scription Example Re sult

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)

he l p( f unc ) Re turns docume ntation of func he l p( s t r . uppe r ( ) ) ' . . . t o uppe r c a s e . '

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 '

Unpacking argume nts Use a se que nce as function argume nts de f f ( x, y, z ) : r e t ur n x + y * z


via aste risk ope rator *. Use a dictionary f ( *[ 1, 3, 4] ) 13
(ke y, value ) via double aste risk ope rator ** f ( **{' z ' : 4, ' x' : 1, ' y' : 3}) 13

Exte nde d Unpacking Use unpacking for multiple assignme nt a , *b = [ 1, 2, 3, 4, 5] a = 1


fe ature in Python b = [ 2, 3, 4, 5]

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}

(Tap here) Join WhatsApp for more such FREE stuff


Python Cheat Sheet: 14 Interview
Questions
A puzzle a day to learn, code, and play
Question Code Question Code

Check if list l = [3, 3, 4, 5, 2, 111, 5] Get missing def get_missing_number(lst):


contains print(111 in l) # True number in return set(range(lst[len(lst)-1])[1:]) - set(l)
integer x [1...100] l = list(range(1,100))
l.remove(50)
print(get_missing_number(l)) # 50

Find duplicate def find_duplicates(elements): Compute def intersect(lst1, lst2):


number in duplicates, seen = set(), set() the res, lst2_copy = [], lst2[:]
integer list for element in elements: intersection for el in lst1:
if element in seen: of two lists if el in lst2_copy:
duplicates.add(element) res.append(el)
seen.add(element) lst2_copy.remove(el)
return list(duplicates) return res

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

Remove all lst = list(range(10)) + list(range(10)) Reverse def reverse(string):


duplicates from lst = list(set(lst)) string using if len(string)<=1: return string
return reverse(string[1:])+string[0]
list print(lst) recursion
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(reverse("hello")) # olleh

Find pairs of def find_pairs(l, x): Compute a, b = 0, 1


integers in list pairs = [] the first n n = 10
so that their for (i, el_1) in enumerate(l): Fibonacci for i in range(n):
sum is equal to for (j, el_2) in enumerate(l[i+1:]): numbers print(b)
integer x if el_1 + el_2 == x: a, b = b, a+b
pairs.append((el_1, el_2)) # 1, 1, 2, 3, 5, 8, ...
return pairs

Check if a def is_palindrome(phrase): Sort list with def qsort(L):


string is a return phrase == phrase[::-1] Quicksort if L == []: return []
palindrome print(is_palindrome("anna")) # True algorithm return qsort([x for x in L[1:] if x< L[0]]) + L[0:1] +
qsort([x for x in L[1:] if x>=L[0]])
lst = [44, 33, 22, 5, 77, 55, 999]
print(qsort(lst))
# [5, 22, 33, 44, 55, 77, 999]

Use list as # as a list ... Find all def get_permutations(w):


stack, array, l = [3, 4] permutation
if len(w)<=1:
and queue l += [5, 6] # l = [3, 4, 5, 6] s of string
return set(w)
# ... as a stack ... smaller = get_permutations(w[1:])
l.append(10) # l = [4, 5, 6, 10] perms = set()
l.pop() # l = [4, 5, 6] for x in smaller:
for pos in range(0,len(x)+1):
# ... and as a queue perm = x[:pos] + w[0] + x[pos:]
l.insert(0, 5) # l = [5, 4, 5, 6] perms.add(perm)
l.pop() # l = [5, 4, 5] return perms
print(get_permutations("nan"))
# {'nna', 'ann', 'nan'}

(Tap here) Join WhatsApp for more such FREE stuff


Python Cheat Sheet: NumPy
“A puzzle a day to learn, code, and play
A puzzle a day to le arn, code , and play →Visit finxte r.com
Name De scription Example

a . s ha pe The shape attribute of NumPy array a ke e ps a tuple of a = np. a r r a y( [ [ 1, 2] , [ 1, 1] , [ 0, 0] ] )


inte ge rs. Each inte ge r de scribe s the numbe r of e le me nts of pr i nt ( np. s ha pe ( a ) ) # ( 3, 2)
the axis.

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. va r ( a ) Calculate s the variance of a numpy array. a = np. a r r a y( [ 2, 6] )


pr i nt ( np. va r ( a ) ) # 4. 0

np. s t d( a ) Calculate s the standard de viation of a numpy array pr i nt ( np. s t d( a ) ) # 2. 0

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. ma x( a ) Re turns the maximal value of NumPy array a. a = np. a r r a y( [ 10, 3, 7, 1, 0] )


pr i nt ( np. ma x( a ) ) # 10

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]

(Tap here) Join WhatsApp for more such FREE stuff


Python Cheat Sheet: Object Orientation Terms
“A puzzle a day to learn, code, and play”
A puzzle a day to le arn, code , and play →Visit finxte r.com
De scription Example

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): ..."

(Tap here) Join WhatsApp for more such FREE stuff


[MachineLearning Cheat Sheet] Support Vector Machines

MachineLearning Classification Support Vector MachineClassification


Computer Scientist Support vectors

Artist

Logic skills
Logic skills

Decision boundary
Decision
boundaries

Creativity skills Creativity skills

WhatarebasicSVM properties? What‘stheexplanationofthecode example?


Support Vector Machines Explanation: A Study Recommendation System with SVM
Alternatives: SVM, support-vectornetworks
Learning:Classification, Regression •NumPy array holds labeled training data (one row per user and one
Advantages:Robust forhigh-dimensional space column per feature).
Memory efficient(onlyusessupport vectors)
Flexible and customizable •Features: skill level in maths, language, and creativity.
Disadvantages:Danger ofoverfittingin high-dimensional space
•Labels: last column is recommended study field.
Noclassificationprobabilitieslike Decisiontrees
Boundary:Linear and Non-linear •3D data →SVM separates data using 2D planes (the linear separator)
rather than 1D lines.
•One-liner:
What‘sthemostbasicPython code example? 1.Create model using constructor of scikit-learn’ssvm.SVCclass
## Dependencies (SVC = support vector classification).
from sklearn im por svm 2.Call fit function to perform training based on labeled training
import numpy tnpas
data.
•Results: call predict function on new observations
## Data: student scores in (math, language, creativity)
•student_0 (skills maths=3, language=3, and creativity=6) →
## --> study field
X =np.array([[9,5,6,"computer science"], SVM predicts “art”
[10,1,2,"computer science"], •student_1 (maths=8, language=1, and creativity=1) →SVM
[1, 8, 1, "literature"],
predicts“computer science”
[4, 9, 3, "literature"],
[0, 1, 10, "art"], •Final output of one-liner:
[5, 7, 9, "art"]])

## 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)

(Tap here) Join WhatsApp for more such FREE stuff


Python Che at She e t: List Me thods
f

Method Description Example

l s t . a ppe nd( x ) Appe nds e le me nt xto the list l s t . >>> l = []


>>> l . a ppe nd( 42)
>>> l . a ppe nd( 21)
[ 42, 21]

l s t . c l e ar ( ) Re move s a ll e le me nts from the lis t >>> l s t = [ 1 , 2 , 3 , 4 , 5 ]


ls t–which be come s e mpty. >>> l s t . c l e a r ( )
[]

l s t . c o py( ) Re turns a copy of the lis t l s t . Copie s only >>> l s t = [ 1 , 2 , 3 ]


the lis t, not the e le me nts in the lis t (s ha llow >>> l s t . c o p y ( )
[ 1, 2, 3]
copy).

l s t . c o unt ( x ) Counts the numbe r of occurre nce s of >>> l s t = [ 1 , 2 , 4 2 , 2 , 1 , 4 2 , 4 2 ]


e le me nt xin the list l s t . >>> l s t . c o u n t ( 4 2 )
3
>>> l s t . c o u n t ( 2 )
2

l s t . e x t e nd( i t e r ) Adds a ll e le me nts of a n ite ra ble i t e r (e .g. >>> l s t = [ 1 , 2 , 3 ]


a nothe r lis t) to the lis t l s t . >>> l s t . e x t e n d ( [ 4 , 5 , 6 ] )
[ 1, 2, 3, 4, 5, 6]

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 . i ns e r t ( i , x ) Ins e rts e le me nt xat pos i tion (inde x) i in >>> l s t = [ 1 , 2 , 3 , 4 ]


the lis t l s t . >>> l s t . i n s e r t ( 3 , 9 9 )
[ 1, 2, 3, 99, 4]

l s t . po p( ) Re move s a nd re turns the fina l e le me nt of >>> l s t = [ 1, 2, 3]


the lis t l s t . >>> l s t . pop( )
3
>>> l st
[ 1, 2]

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]

l s t . r e ve r s e ( ) Re ve rs e s the orde r of e le me nts in the lis t >>> l s t = [ 1, 2, 3, 4]


l st . >>> l s t . r e ve r s e ( )
>>> l st
[ 4, 3, 2, 1]

l s t . s or t ( ) S orts the e le me nts in the lis t l s t in >>> l s t = [ 8 8 , 1 2 , 42, 11, 2]


a s ce nding orde r. >>> l s t . s o r t ( )
# [ 2, 11, 12, 42, 88]
>>> l s t . s o r t ( k e y =l a mb d a x : s t r ( x ) [ 0 ] )
# [ 11, 12, 2, 42, 88]

(Tap here) Join WhatsApp for more such FREE stuff


The Ultimate Python Cheat Sheet
Keywords Basic Data Structures
Keyword Description Code Examples Type Description Code Examples

Boolean The Boolean data type is # # Ev a l u a t e s t o Tr u e :


Fa l s e , Boolean data type Fa l s e == ( 1 > 2 )
either Tr u e or Fa l s e . 1 <2 a n d 0 <=1 a n d 3 >2 a n d 2 >=2 a n d 1 ==1
Tr u e Tr u e == ( 2 > 1 )
Boolean operators are a n d 1 ! =0
ordered by priority:
Logical operators # # Ev a l u a t e s t o Fa l s e :
not → a nd → or
a nd, → Both are true Tr u e a n d Tr u e # Tr u e b o o l ( No n e o r 0 o r 0 . 0 o r ' ' or [ ] or
or , → Either is true Tr u e o r Fa l s e # Tr u e {} or s e t ( ) )
not → Flips Boolean n o t Fa l s e # Tr u e
Rule: None, 0, 0.0, empty strings, or empty container
1, 2, 3 types evaluate to False
br e a k Ends loop prematurely wh i l e Tr u e :
br e a k # f i ni t e l oop Integer, An integer is a positive or ## Ar i t h me t i c Op e r a t i ons
Float negative number without x, y = 3, 2
c ont i nue Finishes current loop iteration wh i l e Tr u e : decimal point such as 3 . pr i nt ( x + y) # = 5
c ont i nue pr i nt ( x - y) # = 1
pr i nt ( " 42" ) # de a d c ode Afloat is a positive or pr i nt ( x * y) # = 6
negative number with pr i nt ( x / y) # = 1. 5
cl as s Defines new class c l a s s Co f f e e : floating point precision pr i nt ( x / / y) # = 1
# De f i n e y o u r c l a s s such as 3 . 1 4 1 5 9 2 6 . pr i nt ( x % y) # = 1
pr i nt ( - x) # = -3
de f Defines a new function or class de f s a y_hi ( ) : Integer division rounds pr i nt ( a bs ( - x) ) # = 3
method. pr i nt ( ' hi ' ) toward the smaller integer pr i nt ( i nt ( 3. 9) ) # = 3
(example: 3 / / 2 ==1 ). pr i nt ( f l oa t ( 3) ) # = 3. 0
if, Conditional execution: x = i nt ( i nput ( " ur va l : " ) ) pr i nt ( x ** y) # = 9
el i f , - “if” condition == True? if x > 3: pr i nt ( " Bi g " )
el s e - "elif" condition == True? e l i f x == 3 : pr i nt ( " 3" ) String Python Strings are # # I n d e x i n g a n d Sl i c i n g
- Fallback: else branch el s e: pr i nt ( " Sma l l " ) sequences of characters. s = " Th e y o u n g e s t p o p e wa s 1 1 y e a r s "
s [ 0 ] # ' T'
String Creation Methods: s [ 1: 3] # ' he ' Slice [::2]
f or , # Fo r l o o p # Wh i l e l o o p d o e s s a me
wh i l e f or i i n [ 0, 1, 2] : j = 0 1. Single quotes s [ - 3: - 1] # ' a r '
pr i nt ( i ) wh i l e j < 3 : >>> ' Ye s ' s [ - 3: ] # ' a r s ' 1 2 3 4
pr i nt ( j ) ; j = j + 1 2. Double quotes
>>> " Ye s " x = s . s pl i t ( ) 0 1 2 3
in Sequence membership 4 2 i n [ 2 , 3 9 , 4 2 ] # Tr u e 3. Triple quotes (multi-line) x[ - 2] + " " + x[ 2] + " s " # ' 11 pope s '
>>> " " " Ye s
is Same object memory location y = x = 3 We Ca n " " " # # St r i n g Me t h o d s
x is y # Tr u e 4. String method y = " He l l o wo r l d \ t \ n "
[ 3] i s [ 3] # Fa l s e >>> s t r ( 5 ) == ' 5 ' y . s t r i p ( ) # Re mo v e Wh i t e s p a c e
Tr u e " HI " . l o we r ( ) # Lo we r c a s e : ' h i '
No n e Empty value constant p r i n t ( ) i s No n e # Tr u e 5. Concatenation " h i " . u p p e r ( ) # Up p e r c a s e : ' HI '
>>> " Ma " + " h a t ma " " h e l l o " . s t a r t s wi t h ( " h e " ) # Tr u e
l a mb d a Anonymous function ( l a mb d a x : x +3 ) ( 3 ) # 6 ' Ma h a t ma ' " h e l l o " . e n d s wi t h ( " l o " ) # Tr u e
" h e l l o " . f i n d ( " l l " ) # Ma t c h a t 2
r e t ur n Terminates function. Optional d e f i n c r e me n t ( x ) : Whitespace chars: " c h e a t " . r e p l a c e ( " c h " , " m" ) # ' me a t '
return value defines function r e t ur n x + 1 Newline \ n, ' ' . j o i n ( [ " F" , " B" , " I " ] ) # ' FBI '
result. i n c r e me n t ( 4 ) # r e t u r n s 5 Space \ s, l e n ( " h e l l o wo r l d " ) # Le n g t h : 1 5
Tab \ t " e a r " i n " e a r t h " # Tr u e

Complex Data Structures


Type Description Example Type Description Example

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}

Subscribe to the 11x FREEPython Cheat Sheet Course:


https:/ / blog.finxter.com/ python-cheat-sheets/
(Tap here) Join WhatsApp for more such FREE stuff

You might also like