Basic Data Structures Keywords: Types Evaluate To False
Basic Data Structures Keywords: Types Evaluate To False
Basic Data Structures Keywords: Types Evaluate To False
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}
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
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 linear in the no. list elements.
Set A set is an unordered collection of unique basket = {'apple', 'eggs', 'banana', 'orange'}
elements (“at-most-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 access the (key, value) pairs of a for k, v in calories.items():
Looping 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 """
for creating concrete instances in 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, list(zip(['Alice', 'Anna'], ['Bob', [('Alice', 'Bob'),
i2, ... 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 Want to share files between PC and phone? Run this command in PC’s shell. <P> is any port number 0–65535. Type <
R <P> IP address of 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” → Visit finxter.com
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
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: NumPy
“A puzzle a day to learn, code, and play” → Visit finxter.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
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]