Python Cheatsheet

Here are some neat Python features:

Multiple assignments

# valid assignment
n, m = 0, "abc"

Incrementing

n = n + 1 # good
n += 1 # good
n++ # bad

Conditionals

if n > 0:
	# ...
elif n == 0:
	# ...
else:
	# ...

Logic

and or not

Loops

while n < 5:
	# ...

for i in range(3):
	print(i) # prints -> 0, 1, 2

for i in range(3, 6):
	print(i) # prints -> 3, 4, 5

for i in range(5, 1, -1):
	print(i) # prints -> 5, 4, 3, 2

# Iterate in reverse
for i in reversed(range(6)): # 5, 4, 3, 2, 1, 0
	print(i)

Division

print(5 / 2) # prints -> 2.5
print(5 // 2) # prints -> 2
print(-5 // 2) # prints -> -3 [!warning Not what we expect]
print(int(-5 / 2)) # prints -> -2 - This is always the best way to do it.

Math Helpers

import math

math.floor(3 / 2)
math.ceil(3 / 2)
math.sqrt(2)
math.pow(2, 3)

Max and Min Integer

float("inf")
float("-inf")

Lists / Arrays

# Initialization
arr = [1, 2, 3]

# Can be used as stack
# push -> append and pop
# O(1)
arr.append(4)
arr.pop()

# Insert at an index
# O(n)
arr.insert(i, value)

# Access O(1)
print(arr[i])

# Reassign value O(1)
arr[i] = value

# Initialize with pre-filled values
n = 5
arr = [1] * n # arr = [1, 1, 1, 1, 1]

# Access from the end
arr[-1] # last value
arr[-2] # second last etc

# Slicing
arr[1:3] # index 1 is included and 3 is not

# Reversing an array
arr[::-1]
arr.reverse()

# Sorting an array
arr.sort()
arr.sort(reverse = True)

# Unpacking (left and right should match in number)
a, b, c = [1, 2, 3]

Looping over array

nums = [1, 2, 3]

for n in nums:
	print(n) # n is 1, 2, 3

for i, n in enumerate(nums):
	print(i, n) # i is the index and n is nums[i]

Looping over two arrays

nums1 = [1, 3, 5]
nums2 = [2, 4, 6]
for n1, n2 in zip(nums1, nums2):
	print(n1, n2) # n1 is from nums1 and n2 is from nums2

List Comprehension

arr = [i for i in range(5)] # [0, 1, 2, 3, 4]
arr = [[0] * 4 for i in range(5)] # 2D list of 5 rows of [0, 0, 0, 0]

Strings

# strings are immutable
s = "abc"
s += "d" # creates a new string with all letters and is O(n)

ASCII

ord("a") # gets ASCII value of letter 'a'

Join List of String

arr = ["a", "b"]
delim = ""
delim.join(arr) # creates a new string "ab"

Queues (Double ended queues)

from collections import deque

queue = deque()
queue.append(1)
queue.pop()
queue.appendleft(1)
queue.popleft()

HashSet

# Set has no duplicates
mySet = set()
mySet.add(1)
len(mySet)

print(1 in mySet) # True

set([1, 2])

# set comprehension
mySet = {i for i in range(5)}

# set methods
mySet.remove(1) # raises error if 1 does not exist
mySet.discard(1) # does NOT raise an error if 1 doesnt exist

HashMap

myMap = {}
myMap["alice"] = 88
# OR
myMap = {"alice": 88}
len(myMap) # len of keys

print("alice" in myMap) # True
myMap.pop("alice")

# dict comprehension
# key difference between this and set compre is ":" to indicate key value pair
myMap = {i: 2 * i for i in range(5)} 

for key, value in myMap.items():
	print(key, value) # prints key value pair without order

Tuples

# immutable and can be used as key to a dict
tup = (1, 2, 3)

# tuples can also be added to a set

Heaps

import heapq

minHeap = []
value = 3

# min heap by default but can multiply with -1 at push and pop to make it maxHeap
heapq.heappush(minHeap, value) # O(log n)
minHeap[0] # the minimum value of the heap
heapq.heappop(minHeap) # O(log n)

# initializing min heap from an array
heapq.heapify(arr)

# initializing max heap from an array
arr = [-x for x in arr] # negate all values first
heapq.heapify(arr)

defaultdict

from collections import defaultdict

# prints 0 as thats the default value for int 
# instead of raising a key error
d = defaultdict(int)
print(d["anyKey"])

# can use any datatype as the default factory
# int, str, dict, float, set, tuple, list
d = defaultdict(list) 
# or you can pass on a function reference or a lamda function
# to return your own default value
d = defaultdict(lamda: "Your own default value")

dict().get("key", "defaultValue")

This would be an alternative to using defaultdict

d = dict()

# prints 0 
print(d.get("anyKey", 0))

OrderedDict

from collections import OrderedDict

# remembers the order of insertion
d = OrderedDict()
d['first'] = 1
d['second'] = 2
# current order -> 1, 2

# we can move an item to the last by key
d.move_to_end('first')

# new order -> 2, 1

d.popitem() # defaults to removing the last item
d.popitem(last=False) # removes first item

nonlocal

def outer_function():
x = 10

def inner_function():
    nonlocal x  # Refers to the 'x' in outer_function
    x = x + 5  # Modifies the outer 'x'

inner_function()
print(x)  # Output: 15

outer_function()