Python Cheat Sheet
Python Cheat Sheet
False, True Data values from the data type Boolean False == (1 > 2), True == (2 > 1)
if, elif, else Conditional program execution: program starts with x = int(input("your value: "))
“if” branch, tries the “elif” branches, and finishes with if x > 3: print("Big")
“else” branch (until one branch evaluates to True). elif x == 3: print("Medium")
else: print("Small")
in Checks whether element is in sequence 42 in [2, 39, 42] # True
return Terminates execution of the function and passes the def incrementor(x):
flow of execution to the caller. An optional value after return x + 1
the return keyword specifies the function result. incrementor(4) # returns 5
Python Cheat Sheet - Basic Data Types
“A puzzle a day to learn, code, and play” → Visit finxter.com
Description Example
Boolean The Boolean data type is a truth value, either ## 1. Boolean Operations
True or F alse. 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
Description Example
Removal Removing an element can be slower. [1, 2, 2, 4].remove(1) # [2, 2, 4]
Reversing This reverses the order of list elements. [1, 2, 3].reverse() # [3, 2, 1]
Sorting Sorts a list. The computational complexity [2, 4, 2].sort() # [2, 2, 4]
of sorting is O(n log n) for n list elements.
Set A set is an unordered collection of basket = {'apple', 'eggs', 'banana', 'orange'}
elements. Each can exist only once. same = set(['apple', 'eggs', 'banana', 'orange'])
Dictionary The dictionary is a useful data structure for calories = {'apple' : 52, 'banana' : 89, 'choco' : 546}
storing (key, value) pairs.
Reading and Read and write elements by specifying the print(calories['apple'] < calories['choco']) # True
writing key within the brackets. Use the keys() and calories['cappu'] = 74
elements values() functions to access all keys and print(calories['banana'] < calories['cappu']) # False
values of the dictionary. print('apple' in calories.keys()) # True
print(52 in calories.values()) # True
Dictionary You can loop over the (key, value) pairs of for k, v in calories.items():
Looping a dictionary with the items() method. print(k) if v > 500 else None # 'chocolate'
Membership Check with the ‘in’ keyword whether the basket = {'apple', 'eggs', 'banana', 'orange'}
operator set, list, or dictionary contains an element. print('eggs' in basket} # True
Set containment is faster than list print('mushroom' in basket} # False
containment.
List and Set List comprehension is the concise Python # List comprehension
Comprehens way to create lists. Use brackets plus an l = [('Hi ' + x) for x in ['Alice', 'Bob', 'Pete']]
ion expression, followed by a for clause. Close print(l) # ['Hi Alice', 'Hi Bob', 'Hi Pete']
with zero or more for or if clauses. l2 = [x * y for x in range(3) for y in range(3) if x>y]
print(l2) # [0, 0, 2]
Set comprehension is similar to list # Set comprehension
comprehension. squares = { x**2 for x in [0,2,4] if x < 4 } # {0, 4}
Python Cheat Sheet - Classes
“A puzzle a day to learn, code, and play” → Visit finxter.com
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"]
A map(func, iter) Executes the function on all elements of list(map(lambda x: x[0], ['red', ['r', 'g', 'b']
D the iterable 'green', 'blue']))
V
A map(func, i1, ..., Executes the function on all k elements of list(map(lambda x, y: str(x) + ' ' + ['0 apples', '2
ik) the k iterables y + 's' , [0, 2, 2], ['apple', oranges', '2
N
C 'orange', 'banana'])) bananas']
E
string.join(iter) Concatenates iterable elements ' marries '.join(list(['Alice', 'Alice marries Bob'
D separated by string 'Bob']))
F filter(func, Filters out elements in iterable for which list(filter(lambda x: True if x>17 [18]
U iterable) function returns False (or 0) else False, [1, 15, 17, 18]))
N
C string.strip() Removes leading and trailing print(" \n \t 42 \t ".strip()) 42
T whitespaces of string
I
O sorted(iter) Sorts iterable in ascending order sorted([8, 3, 2, 42, 5]) [2, 3, 5, 8, 42]
N
sorted(iter, Sorts according to the key function in sorted([8, 3, 2 , 42, 5], key=lambda [42, 2, 3, 5, 8]
S
key=key) ascending order x: 0 if x==42 e lse x)
zip(i1, i2, ...) Groups the i-th elements of iterators i1, i2, list(zip(['Alice', 'Anna'], ['Bob', [('Alice', 'Bob'),
… together 'Jon', 'Frank'])) ('Anna', 'Jon')]
Unzip Equal to: 1) unpack the zipped list, 2) zip list(zip(*[('Alice', 'Bob'), [('Alice', 'Anna'),
the result ('Anna', 'Jon')] ('Bob', 'Jon')]
enumerate(iter) Assigns a counter value to each element list(enumerate(['Alice', 'Bob', [(0, 'Alice'), (1,
of the iterable 'Jon'])) 'Bob'), (2, 'Jon')]
T python -m http.server Share files between PC and phone? Run command in PC’s shell. <P> is any port number 0–65535. Type < IP address of
R <P> PC>:<P> in the phone’s browser. You can now browse the files in the PC directory.
I
C Read comic import antigravity Open the comic series xkcd in your web browser
K
S
Zen of Python import this '...Beautiful is better than ugly. Explicit is ...'
Unpacking arguments Use a sequence as function arguments def f(x, y, z): return x + y * z
via asterisk operator *. Use a dictionary f(*[1, 3, 4]) 13
(key, value) via double asterisk operator ** f(**{'z' : 4, 'x' : 1, 'y' : 3
}) 13
Extended Unpacking Use unpacking for multiple assignment a, *b = [1, 2, 3, 4, 5] a = 1
feature in Python b = [2, 3, 4, 5]
Merge two dictionaries Use unpacking to merge two dictionaries x={'Alice' : 18} z = {'Alice': 18,
into a single one y={'Bob' : 27, 'Ann' : 22} 'Bob': 27, 'Ann': 22}
z = {**x,**y}
Python Cheat Sheet: 14 Interview Questions
“A puzzle a day to learn, code, and play” →
*FREE* Python Email Course @ http://bit.ly/free-python-course
Question Code Question Code
Check if list l = [3, 3, 4, 5, 2, 111, 5] Get missing def g et_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
Check if two def i s_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.shape The shape attribute of NumPy array a keeps a tuple of a = np.array([[1,2],[1,1],[0,0]])
integers. Each integer describes the number of elements of print(np.shape(a)) # (3, 2)
the axis.
a.ndim The ndim attribute is equal to the length of the shape tuple. print(np.ndim(a)) # 2
np.matmul(a,b), a@b The standard matrix multiplication operator. Equivalent to the print(np.matmul(a,b))
@ operator. # [[2 2] [2 2]]
np.arange([start, ]stop, Creates a new 1D numpy array with evenly spaced values print(np.arange(0,10,2))
[step, ]) # [0 2 4 6 8]
np.linspace(start, stop, Creates a new 1D numpy array with evenly spread elements print(np.linspace(0,10,3))
num=50) within the given interval # [ 0. 5. 10.]
np.average(a) Averages over all the values in the numpy array a = np.array([[2, 0], [0, 2]])
print(np.average(a)) # 1.0
<slice> = <val> Replace the <slice> as selected by the slicing operator with a = np.array([0, 1, 0, 0
, 0])
the value <val>. a[::2] = 2
print(a) [2 1 2 0 2]
#
np.diff(a) Calculates the difference between subsequent values in fibs = np.array([0, 1
, 1, 2, 3, 5])
NumPy array a print(np.diff(fibs, n=1))
# [1 0 1 1 2]
np.sort(a) Creates a new NumPy array with the values from a a = np.array([10,3,7,1,0])
(ascending). print(np.sort(a))
# [ 0 1 3 7 10]
np.argsort(a) Returns the indices of a NumPy array so that the indexed a = np.array([10,3,7,1,0])
values would be sorted. print(np.argsort(a))
# [4 3 1 2 0]
np.argmax(a) Returns the index of the element with maximal value in the a = np.array([10,3,7,1,0])
NumPy array a. print(np.argmax(a)) # 0
np.nonzero(a) Returns the indices of the nonzero elements in NumPy array a = np.array([10,3,7,1,0])
a. print(np.nonzero(a)) # [0 1 2 3]
Python Cheat Sheet: Object Orientation Terms
“A puzzle a day to learn, code, and play” → Visit finxter.com
Description Example
Class A blueprint to create objects. It defines the data (attributes) and functionality og:
class D
(methods) of the objects. You can access both attributes and methods via
the dot notation. # class attribute
is_hairy = True
Object A piece of encapsulated data with functionality in your Python program that
(=instance) is built according to a class definition. Often, an object corresponds to a # constructor
def __init__(self, name):
thing in the real world. An example is the object "Obama" that is created
# instance attribute
according to the class definition "Person". An object consists of an arbitrary
self.name = name
number of attributes and methods, encapsulated within a single unit.
# method
Instantiation The process of creating an object of a class. This is done with the
def bark(self):
constructor method __init__(self, …). print("Wuff")
Self The first argument when defining any method is always the self argument. print(bello.name)
"bello"
This argument specifies the instance on which you call the method.
self gives the Python interpreter the information about the concrete print(paris.name)
"paris"
instance. To define a method, you use self t o modify the instance
n instance method, you do not need to specify self.
attributes. But to call a
at:
class C
Encapsulation Binding together data and functionality that manipulates the data.
# method overloading
Attribute A variable defined for a class (class attribute) or for an object (instance attribute). You def miau(self, times=1):
use attributes to package data into enclosed units (class or instance). print("miau " * times)
Class (=class variable, static variable, static attribute) A variable that is created fifi = Cat()
attribute statically in the class definition and that is shared by all class objects.
fifi.miau()
Instance A variable that holds data that belongs only to a single instance. Other instances do "miau "
attribute not share this variable (in contrast to class attributes). In most cases, you create an
(=instance instance attribute x in the constructor when creating the instance itself using the self fifi.miau(5)
variable) "miau miau miau miau miau "
keywords (e.g. self.x = <val>).
# Dynamic attribute
fifi.likes = "mice"
Dynamic An instance attribute that is defined dynamically during the execution of the program print(fifi.likes)
attribute and that is not defined within any method. For example, you can simply add a new "mice"
attribute neew to any object o by calling o.neew = <val>.
# Inheritance
Method You may want to define a method in a way so that there are multiple options ersian_Cat(Cat):
class P
overloading to call it. For example for class X, you define a method f(...) that can be called classification = "Persian"
in three ways: f(a), f(a,b), or f(a,b,c). To this end, you can define the method
mimi = Persian_Cat()
with default parameters (e.g. f(a, b=None, c=None).
print(mimi.miau(3))
"miau miau miau "
Inheritance Class A can inherit certain characteristics (like attributes or methods) from class B.
For example, the class "Dog" may inherit the attribute "number_of_legs" from the
class "Animal". In this case, you would define the inherited class "Dog" as follows: print(mimi.classification)
"class Dog(Animal): ..."
[Test Sheet] Help Alice Find Her Coding Dad!
+ BONUS
+ BONUS
Solve puzzle 369!
+ BONUS
Support vector
A: 50𝑚2 , $34,000
Logic skills
B: 55𝑚2 , $33,500
House Price ($)
C: 45𝑚2 , $32,000
A
B
$99,500
D‘: 52𝑚2 ,
3 Decision
C 3NN
≈ (52𝑚2 , $33,167)
boundary
Computer Scientist
D: (52𝑚2 , ? ) Artist
House Size (square meter)
Creativity skills
Like maths?
N
Y
„Study art!“
„Study history!“
Remote Repository:
Master Branch
Alice Bob
git init
Clone repository
Clone
git add main.py </> git clone bob@host:/path/repos
Add file „main.py“ to project
„new file“
Pull
git pull </>
Main idea: Maximize width of separator zone → increases „margin of safety“ for classification
Artist
Logic skills
Logic skills
Decision boundary
Decision
boundaries
What are basic SVM properties? What‘s the explanation of the code example?
Support Vector Machines Explanation: A Study Recommendation System with SVM
Alternatives: SVM, support-vector networks
Learning: Classification, Regression • NumPy array holds labeled training data (one row per user and one
Advantages: Robust for high-dimensional space column per feature).
Memory efficient (only uses support vectors)
Flexible and customizable • Features: skill level in maths, language, and creativity.
Disadvantages: Danger of overfitting in high-dimensional space
No classification probabilities like Decision trees • Labels: last column is recommended study field.
Boundary: Linear and Non-linear
• 3D data → SVM separates data using 2D planes (the linear separator)
rather than 1D lines.
lst.clear() Removes all elements from the list >>> lst = [1, 2, 3, 4, 5]
lst–which becomes empty. >>> lst.clear()
[]
lst.copy() Returns a copy of the list lst. Copies only >>> lst = [1, 2, 3]
the list, not the elements in the list (shallow >>> lst.copy()
[1, 2, 3]
copy).
lst.count(x) Counts the number of occurrences of >>> lst = [1, 2, 42, 2, 1, 42, 42]
element x in the list lst. >>> lst.count(42)
3
>>> lst.count(2)
2
lst.extend(iter) Adds all elements of an iterable iter (e.g. >>> lst = [1, 2, 3]
another list) to the list lst. >>> lst.extend([4, 5, 6])
[1, 2, 3, 4, 5, 6]
lst.index(x) Returns the position (index) of the first >>> lst = ["Alice", 42, "Bob", 99]
occurrence of value x in the list lst. >>> lst.index("Alice")
0
>>> lst.index(99, 1, 3)
ValueError: 99 is not in list
lst.pop() Removes and returns the final element of >>> lst = [1, 2, 3]
the list lst. >>> lst.pop()
3
>>> lst
[1, 2]
lst.remove(x) Removes and returns the first occurrence >>> lst = [1, 2, 99, 4, 99]
of element x in the list lst. >>> lst.remove(99)
>>> lst
[1, 2, 4, 99]
lst.reverse() Reverses the order of elements in the list >>> lst = [1, 2, 3, 4]
lst. >>> lst.reverse()
>>> lst
[4, 3, 2, 1]
lst.sort() Sorts the elements in the list lst in >>> lst = [88, 12, 42, 11, 2]
ascending order. >>> lst.sort()
# [2, 11, 12, 42, 88]
>>> lst.sort(key=lambda x: str(x)[0])
# [11, 12, 2, 42, 88]
The Ultimate Python Cheat Sheet
Keywords Basic Data Structures
Keyword Description Code Examples Type Description Code Examples
List Stores a sequence of l = [1, 2, 2] Dictionary Useful data structure for cal = {'apple' : 52, 'banana' : 89,
elements. Unlike strings, you print(len(l)) # 3 storing (key, value) pairs 'choco' : 546} # calories
can modify list objects (they're
Reading Read and write elements by print(cal['apple'] < cal['choco'])
mutable).
and specifying the key within the # True
Adding Add elements to a list with (i) [1, 2].append(4) # [1, 2, 4] writing brackets. Use the keys() cal['cappu'] = 74
elements append, (ii) insert, or (iii) list [1, 4].insert(1,9) # [1, 9, 4] elements and values() functions to print(cal['banana'] < cal['cappu'])
concatenation. [1, 2] + [4] # [1, 2, 4] access all keys and values of # False
the dictionary
print('apple' in cal.keys()) # True
Removal Slow for lists [1, 2, 2, 4].remove(1) # [2, 2, 4]
print(52 in cal.values()) # True
Reversing Reverses list order [1, 2, 3].reverse() # [3, 2, 1]
Dictionary You can access the (key, for k, v in cal.items():
Sorting Sorts list using fast Timsort [2, 4, 2].sort() # [2, 2, 4] Iteration value) pairs of a dictionary print(k) if v > 500 else ''
with the items() method. # 'choco'
Indexing Finds the first occurrence of [2, 2, 4].index(2)
an element & returns index. # index of item 2 is 0 Member- Check with the in keyword if basket = {'apple', 'eggs',
Slow worst case for whole list [2, 2, 4].index(2,1) ship set, list, or dictionary contains 'banana', 'orange'}
traversal. # index of item 2 after pos 1 is 1 operator an element. Set membership print('eggs' in basket) # True
is faster than list membership. print('mushroom' in basket) # False
Stack Use Python lists via the list stack = [3]
operations append() and pop() stack.append(42) # [3, 42] List & set List comprehension is the l = ['hi ' + x for x in ['Alice',
stack.pop() # 42 (stack: [3]) comprehe concise Python way to create 'Bob', 'Pete']]
stack.pop() # 3 (stack: []) nsion lists. Use brackets plus an # ['Hi Alice', 'Hi Bob', 'Hi Pete']
expression, followed by a for
Set An unordered collection of basket = {'apple', 'eggs', clause. Close with zero or l2 = [x * y for x in range(3) for y
unique elements (at-most- 'banana', 'orange'} more for or if clauses. in range(3) if x>y] # [0, 0, 2]
once) → fast membership O(1) same = set(['apple', 'eggs', Set comprehension works
squares = { x**2 for x in [0,2,4]
'banana', 'orange']) similar to list comprehension.
if x < 4 } # {0, 4}
→ Complexity reduces productivity and focus. It’ll consume your precious time. Keep it simple!