Skip to content

Python

Cheatsheet

Iteration

Iterate Array with Index

my_array = [1, 2, 3, 4, 5]
for index, element in enumerate(my_array):
print(index, element)

Iterate Array/String

my_string = "Hello, World!"
for char in my_string:
print(char)

Loop

while list1 or list2:
# do something if list1 or list2 are not empty
for i in range(6):
print(i) # will print 0 to 5

Array

Basic Array Operations

arr = [1, 2, 3, 4, 5]
print(arr[::-1])
# [5, 4, 3, 2, 1]
print(arr[2:])
# [3, 4, 5]
print(arr[:2])
# [1, 2]
# create array with value of 0 and length of 10
arr = [0] * 10

Map/Dictionary

Basic Dictionary Operations

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
# get key
# if key1 not exists, will return default_value
my_dict.get('key1', 'default_value')
my_dict['key1']
my_dict['key1_notexists'] # will raise KeyError if not exists
# delete element
del my_dict['key2']
# get all values
my_dict.values()
# get all keys
my_dict.keys()

Check Key/Value Exists in Dictionary

my_map = {"key1": 1, "key2": 2, "key3": 3}
# Check if a key exists in the map
if "key2" in my_map:
print("Key 'key2' exists in the map")
# Check if a value exists in the map
if 2 in my_map.values():
print("Value 2 exists in the map")

Default Value for Dictionary

from collections import defaultdict
# Function to return a default
# value for keys that are not
# present
def def_value():
return "Not Present"
# Defining the dict
d = defaultdict(def_value)
d["a"] = 1
d["b"] = 2
print(d["a"]) # 1
print(d["b"]) # 2
print(d["c"]) # Not Present

Set

Basic Set Operations

hashset = set()
# Adding elements to the hash set
hashset.add(5)
hashset.add(10)
hashset.add(15)
# Checking if an element exists in the hash set
if 10 in hashset:
print("10 exists in the hash set")
# Removing an element from the hash set
hashset.remove(5)
# Iterating over the hash set
for element in hashset:
print(element)

Stack

Basic Stack Operations

stack = []
stack.append(1) # Pushes 1 onto the stack
stack.append(2) # Pushes 2 onto the stack
top_element = stack.pop() # Removes and returns the top element
print(top_element) # Outputs: 2
if len(stack) == 0:
print("Stack is empty")
if not stack:
print("Stack is empty")

Bit and Binary Operations

# XOR
1 ^ 2 # 1 XOR 2 -> 3 (BINARY: 1 XOR 10 -> 11)
# right bitwise
8 >> 1 # 1000 -> 4 (BINARY: 1000 shift to right 1 time -> 100)
7 >> 1 # 111 -> 3 (BINARY: 111 shift to right 1 time -> 11)
# bit mask
8 & 1 # 1000 AND 1 -> 0
3 & 1 # 11 AND 1 -> 1
n = 0
print(n | 1) # add 1 to right most bit
a = 42
print(bin(a)) # 0b101010

Helpful Functions

Math Functions

max(a, b)
min(a, b)
# absolute
a = -12
print(abs(a)) # 12
# power
print(2 ** 4) # 16
# division
a = 5
print(a / 2) # 2.5
print(a // 2) # 2

String Functions

"string".islower() # is lowercase
"string".isdigit() # is number
"string".isalpha() # is string
"string".isalnum() # is number or string
"string".lower() # lowercase

Sorting

a = [1, 3, 4, 2]
# this will change the a directly and return nothing
a.sort()
print(a) # [1,2,3,4]
a.sort(reverse=True)
print(a) # [4,3,2,1]
print(sorted(a)) # [1,2,3,4]
# custom sort logic
points = [[1, 2], [3, 4]]
def logic(e: List[int]):
return e[0]**2 + e[1]**2 # a^2 + b^2
print(sorted(points, key=logic))

Conditional Logic

# if logic
if a < b < c:
print(b)
# ternary
x = 5
result = "Even" if x % 2 == 0 else "Odd"
print(result) # Odd
# select element from tuple
a = 1
b = 2
c = (a, b)[a > b]
# (a, b) -> array [a,b]
# [a > b] -> True will be index 1, False will be index 0
print(c) # 2

Counter

from collections import Counter
a = "hello world!"
print(Counter(a))
# Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1, '!': 1})

Sort

Sort by Value and Key in Decreasing Order

class Solution:
def frequencySort(self, nums: List[int]) -> List[int]:
dic = Counter(nums)
nums.sort(key=lambda x: (dic[x], -x))
return nums