Python Cheat Sheet - Functions and Tricks
“A puzzle a day to learn, code, and play” → Visit f inxter.com
Description Example Result
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 else x)
help(func) Returns documentation of func help(str.upper()) '... to uppercase.'
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 ...'
Swapping numbers Swapping variables is a breeze in Python. a, b = 'Jane', 'Alice' a = 'Alice'
No offense, Java! a, b = b, a b = 'Jane'
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 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
list print(lst) recursion return reverse(string[1:])+string[0]
# [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)
smaller = get_permutations(w[1:])
# ... as a stack ... perms = set()
l.append(10) # l = [4, 5, 6, 10] for x in smaller:
l.pop() # l = [4, 5, 6] for pos in range(0,len(x)+1):
perm = x[:pos] + w[0] + x[pos:]
# ... and as a queue perms.add(perm)
l.insert(0, 5) # l = [5, 4, 5, 6] return perms
l.pop() # l = [5, 4, 5] print(get_permutations("nan"))
# {'nna', 'ann', 'nan'}
Python Cheat Sheet: NumPy
“A puzzle a day to learn, code, and play” → Visit f inxter.com
Name Description Example
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
* The asterisk (star) operator performs the Hadamard product, a = np.array([[2, 0], [0, 2]])
i.e., multiplies two matrices with equal shape element-wise. b = np.array([[1, 1], [1, 1]])
print(a*b) # [[2 0] [0 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.var(a) Calculates the variance of a numpy array. a = np.array([2, 6])
print(np.var(a)) # 4.0
np.std(a) Calculates the standard deviation of a numpy array print(np.std(a)) # 2.0
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.cumsum(a) Calculates the cumulative sum of the elements in NumPy print(np.cumsum(np.arange(5)))
array a. # [ 0 1 3 6 10]
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.max(a) Returns the maximal value of NumPy array a. a = np.array([10,3,7,1,0])
print(np.max(a)) # 10
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 f inxter.com
Description Example
Class A blueprint to create o bjects. It defines the data (attributes) and functionality class Dog:
(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) efinition. Often, an object corresponds to a
is built according to a c lass d # 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 a ttributes a
nd m
ethods, e ncapsulated w
ithin a single unit.
# method
Instantiation bject of a c lass. This is done with the
The process of creating an o
def bark(self):
constructor method __init__(self, …). print("Wuff")
Method A subset of the overall functionality of an object. The method is defined
similarly to a function (using the keyword "def") in the c lass definition. An bello = Dog("bello")
object can have an arbitrary number of methods. paris = Dog("paris")
Self The first argument when defining any method is always the s elf argument. print(bello.name)
"bello"
n which you call the m
This argument specifies the i nstance o ethod.
self gives the Python interpreter the information about the concrete print(paris.name)
"paris"
instance. To define a method, you use s elf to modify the instance
attributes. But to call an instance method, you do not need to specify s
elf.
class Cat:
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 class Persian_Cat(Cat):
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): ..."