Python cheatsheet
Python cheatsheet
int(“15”) → 15 LST=[10, 20, 30, 40, 50] list = [i for i in range(11) if i % 2 == 0] even list
int(“3f”,16) → 63 can specify integer number base len(lst)→ 5 list length matrix = [[j for j in range(3)] for i in range(3)]
in 2nd parameter lst[start slice:end slice:step] numbers = [1, 2, 3, 4, 5] squared = [x ** 2 for x in numbers]
int(15.56) → 15 truncate decimal part lst[:-1]→[10,20,30,40] expr for elem in iterable if mytest new list based on test
float(“-11.24e8”) → -1124000000.0 lst[::2]→[10,30,50]
round(15.56,1)→ 15.6 rounding to 1 decimal (0 lst[:]→[10,20,30,40,50] shallow copy ASSERTION
decimal → integer number) del lst[3:5] delete def f(L, val):
bool(x) False for null x, empty container x , lst[1:4]=[15,25] modify with assignment assert len(L) != 0, ‘list is empty’
None or False x ; True for other x ROUNDING INPUT assert (type(val)==int), ‘val is a non-number’
str(x)→ “…” representation string of x for dis- ceil(12.5)→13 s = input(“Instructions:”) for e in L:
play (cf. formatting on the back) floor(12.5)→12 *always return str = convert assert (type(e)==int), ‘non-number found in L’
chr(64)→’@’ ord(‘@’)→64 code ↔ char LIST OPERATIONS if e >= val:
SPECIAL CLASS OPERATORS
repr(x)→ “…” literal representation string of x lst.append(val) add item at end return False
object.__lt__(self, other)
bytes([72,9,64]) → b’H\t@’ lst.extend(seq) add sequence of items at end return sum(L)/len(L)
object.__le__(self, other)
list(“abc”) → [‘a’,’b’,’c’] lst.insert(idx,val) insert item at index TRY EXCEPT object.__mul__(self, other)
dict([(3,”three”),(1,”one”)]) → lst.remove(val) remove first item with value val try:
object.__truediv__(self, other)
{1:’one’,3:’three’} lst.pop([idx])→value remove & return item at a = int(input("Tell me one number: ")) object.__eq__(self, other)
set([“one”,”two”]) → {‘one’,’two’} index idx (default last) b = int(input("Tell me another number: ")) object.__ne__(self, other)
separator str and sequence of str → assembled str lst.sort() lst.reverse()list in place print("a + b =", a + b) object.__gt__(self, other)
‘:’.join([‘toto’,’12’,’pswd’]) → ‘toto:12:pswd’ list.sort(reverse=True|False, key=myFunc) print("a / b =", a / b) object.__ge__(self, other)
str splitted on whitespaces → list of str GENERIC OPERATIONS IN CONTAINERS except ValueError: object.__len__(self)
“words with spaces”.split() → len(c)→ items count print("Could not convert to a number.")
[‘words’,’with’,’spaces’] min(c) max(c) sum(c) except:
str splitted on separator str → list of str sorted(c)→ list sorted copy print("Something went very wrong.")
“1,4,8,2”.split(“,”) → [‘1’,’4’,’8’,’2’] val in c → boolean, membership operator in (ab- else:
sequence of one type → list of another type (via sence not in) print(“only runs inf no except block was executed”)
list comprehension) enumerate(c)→ iterator on (index, value) finally:
[int(x) for x in (‘1’,’29’,’-3’)] → [1,29,-3] zip(c1,c2…)→ iterator on tuples containing ci print(“executed independent of success”)
OPERATIONS ON OPERATIONS ON SETS items at same index Enforce valid user input within finite tries NEWTON-RAPHSON for square root
DICTIONARIES | → union (vertical bar def get_value(val_type, request, num_tries): epsilon = 0.01
d[key]=value char) Specific to ordered sequences containers (lists, for i in range(num_tries): guess = k/2
d[key]→ value & → intersection tuples, strings, bytes…) in_val = input(request) while abs(guess**2 - k) >= epsilon:
iterable views - ^ → difference/ reversed(c)→ inversed iterator c*5→ duplicate try: guess = guess - (((guess**2) -
on keys/values/ symmetric diff. c+c2→ concatenate return val_type(in_val) k)/(2*guess))
associations < <= > >= → inclusion c.index(val)→ position except:
d.keys() relations c.count(val) print(f”Invalid input. You get {num_tries - i - 1} more attempts.”)
d.values()→ s.update(s2) s.copy() all(c)→ True if all c items evaluated to true, raise ValueError(in_val, f”Last input was ‘{in_val}’”)
d.items() s.add(key) s.remove(key) else False def squared(numbers):
d.clear() s.discard(key) s.clear() any(c)→ True if at least one item of c evaluated if not isinstance(numbers, list | tuple):
del d[key] s.pop() true, else False raise TypeError(f”list or tuple expected, got ‘{type(numbers).__name__}’”)
d.pop(key[,default])→ return [number**2 for number in numbers]
value import copy s.capitalize()
d.popitem()→ copy.copy(c)→ shallow copy of container OPERATIONS ON STRINGS s.casefold()
(key,value) copy.deepcopy(c)→ deep copy of containe s.startswith(prefix[,start[,end]]) s.center(length, char)
d.get(key[,default])→ F-STRINGS s.endswith(suffix[,start[,end]]) s.isalnum()
value f”My name is {full_name} which is {len(full_ s.strip([chars]) s.isalpha()
INTEGER SEQUENCES name)} characters long.” variables s.count(value, start, end) s.isascii()
range([start,] end [,step]) f”Two digits: {n:.2f} and {pi:.2f}” round to two s.partition(sep)→ (before,sep,after) s.isdescimal()
range(5)→ 0 1 2 3 4 range(2,12,3)→ 2 5 8 11 decimal places s.index(sub[,start[,end]]) s.isdigit()
range(3,8)→ 3 4 5 6 7 range(20,5,-5)→ 20 15 10 (f”{name1}\n” s.find(sub[,start[,end]]) s.isidentifier()
range(len(seq))→ sequence of index of values in f”{name2}” s.upper() s.lower() s.title() s.swapcase() s.islower()
seq ) multiline s.ljust([width,fill]) s.rjust([width,fill]) s.isnumeric()
* range provides an immutable sequence of int LAMBDA s.zfill([width]) s.isprintable()
constructed as needed x = lambda a : a + 10 >> print(x(5)) s.encode(encoding) s.split([sep]) s.join(seq) s.isspace()
d = {‘a’: 1, ‘b’: 2} >> values = s.split(separator, maxsplit) s.isupper()
map(lambda key: d[key], d.keys()) s.splitlines(keeplinebreaks)
def binary_search_iterative(L, x):
print(f”{L = }”) class Animal:
COMPLEXITY BISECTION SEARCH lo, hi = 0, len(L) def __init__(self, age): RECURSION
Assignment: O(1) x = 0.25 if hi == 0: self.age = age def fact(n):
Basic oper: O(1) epsilon = 0.01 return False self.name = None if n == 1:
Lists/Tuples num_guesses = 0 while hi - lo > 1: def get_age(self): return 1
index: O(1) if x >= 1: mid = (lo + hi) // 2 return self.age else:
store: O(1) low = 1 if L[mid] > x: def get_name(self): return n * fact(n - 1)
length: O(1) high = x hi = mid return self.name def deep_rev (L):
append: O(1) else: else: def set_age(self, newage): if L == []:
pop(): O(1) low = x lo = mid self.age = newage return L
clear: O(1) high = 1 return L[lo] == x def set_name(self, newname=""): elif type(L[0]) == list:
check l1==l2: O(n) ans = (low + high) / 2 self.name = newname return depp_rev(L[1:]) + [deep_rev(L[0])]
insert: O(n) while abs(ans**2 - x) >= epsilon: def __str__(self): else:
delete: O(n) print(f"low = {low}, high = {high}, ans = return f"<Animal {self.get_name()} {self.get_age()}>" return deep_rev(L[1:]) + [L[0]]
class Rabbit(Animal): def my_deep_copy(L):
in/not int: O(n) {ans}")
tag = 1 # a class variable, accessible (readable-only) if L == []:
copy: O(n) if ans**2 < x:
from all instances return L
remove: O(n) low = ans
def __init__(self, age, parent1=None, parent2=None): elif type(L[0]) == list:
pop(i): O(n) else:
super().__init__(age) return [my_deep_copy(L[0])] + my_deep_
max/min: O(n) high = ans
self.parent1 = parent1 copy(L[1:])
reverse: O(n) ans = (low + high) / 2
self.parent2 = parent2 else:
for loop: O(n) num_guesses += 1
self.rid = Rabbit.tag return [L[0]] + my_deep_copy(L[1:])
sort: O(nlogn) print(f"{num_guesses = }")
Rabbit.tag += 1 def flatten(L):
multiply l*k: O(n k) print(f"{ans} is close to square root of {x}")
def get_rid(self): flattened_list = []
slice[a:b]: O(b-a)
return str(self.rid).zfill(5) for item in L:
extend(...): O(len(...))
def get_parent1(self): if isinstance(item, list):
construction(...): O(len(...))
return self.parent1 flattened_list.extend(flatten(item))
Dictionary def permutation(lst): def get_parent2(self): else:
index: O(1) if len(lst) == 0: return self.parent2 flattened_list.append(item)
store: O(1) return [] def __add__(self, other): return flattened_list
length: O(1) if len(lst) == 1: return Rabbit(0, self, other) def count_in(L, e):
delete: O(1) return [lst] def __eq__(self, other): if len(L) == 1:
get/set: O(1) l = [] parents_same_order = (self.get_parent1().get_rid() if type(L[0]) == int:
pop: O(1)
== other.get_parent1().get_rid() and self.get_parent2(). if e == L[0]:
clear: O(1) for i in range(len(lst)): get_rid() == other.get_parent2().get_rid()) return 1
.keys: O(1) m = lst[i] parents_swapped_order = (self.get_parent2().get_ else:
iter for loop: O(n) remLst = lst[:i] + lst[i+1:] rid() == other.get_parent1().get_rid() and self.get_par- return 0
construction(...): O(len(...))
ent1().get_rid() == other.get_parent2().get_rid()) elif type(L[0]) == list:
Search for p in permutation(remLst): return parents_same_order or parents_swapped_order return count_in(L[0], e)
binary search: O(sort)+O(logn) l.append([m] + p) def __str__(self): else:
mergesort: O(nlogn) return l return f"rabbit:{self.get_rid()}" if type(L[0]) == int:
bubbblesort: O(n*2)
convert to binary if first: if L[0] == e:
def max_contig_subseq_sum(L): return 1 + count_in(L[1:], e)
binary = "" binary += '1'+str((bigges-
max_so_far =L[0] else:
biggesti = n ti)*'0')
curr_max = L[0] return count_in(L[1:], e)
i = n lengthbinary = biggesti+1
for i in range(1, len(L)): elif type(L[0]) == list:
found = False first = False
curr = L[i] return count_in(L[0], e) + count_
first = True else:
i_now = curr_max + L[i] in(L[1:], e)
lengthbinary = 0 binary = binary[0:(length-
curr_max = max(L[i], i_now) def sum_lengths(L):
if n == 0: binary-biggesti-1)]+'1'+binary[(length-
max_so_far = max(max_so_far,curr_max) total = 0
print(0) binary-biggesti):]
return max_so_far for e in L:
CARTESIAN PRODUCT if n == 1: n = n - 2**biggesti
list3 = [i+str(j) for i in list1 for j in list2] print(1) i = n if type(e) == str:
while True: biggesti = n total += len(e)
while i > 0: found = False elif type(e) == list:
if 2**i <= n: if n == 0: total += sum_lengths(e)
biggesti = i binary = binary[0:-1] + '0' return total
found = True break
break if n == 1:
i -= 1 binary = binary[0:-1] + '1'
if found: break