https://claude.site/artifacts/2dedcd72-1568-45e6-8b86-219c5c733ef8

Python Interview Cheatsheet

Essential Syntax

# Variables are dynamically typed
n = 0                  # Integer
n = "abc"              # String
n, m, z = 0.125, "abc", False  # Multiple assignments

# Increment
n = n + 1             # Good
n += 1                # Good
n++                   # Bad (doesn't work in Python)

# None (null value)
n = None

# Print
print("Hello", end='')  # No newline
print("World!", end='\\n')  # With newline (default)

Control Flow

# If-else (no parentheses needed)
if n > 2:
    n -= 1
elif n == 2:
    n *= 2
else:
    n += 2

# Multiple conditions (use 'and'/'or' instead of &&/||)
if (n > 2 and n != m) or n == m:
    n += 1

# While loop
while n < 5:
    print(n)
    n += 1

# For loop
for i in range(5):        # 0 to 4
    print(i)
for i in range(2, 6):     # 2 to 5
    print(i)
for i in range(5, 1, -1): # 5 to 2 (reverse)
    print(i)

Data Structures

Lists (Dynamic Arrays)

# Creation and operations
arr = [1, 2, 3]
arr.append(4)           # Add to end
arr.extend([5, 6])      # Add multiple elements
arr.insert(1, 42)       # Insert at index 1
arr.remove(3)           # Remove first occurrence of value
arr.pop()               # Remove from end
arr.pop(0)              # Remove at index 0
arr.clear()             # Remove all elements

# List methods
arr.index(42)           # Find index of value (errors if not found)
arr.count(3)            # Count occurrences
arr.reverse()           # Reverse in place
arr.sort()              # Sort in place
arr.sort(reverse=True)  # Sort descending

# List operations
arr1 + arr2             # Concatenate lists
arr * 3                 # Repeat list
len(arr)                # Get length
min(arr)                # Get minimum value
max(arr)                # Get maximum value
sum(arr)                # Sum all elements

# List comprehension
arr = [i for i in range(5)]  # [0, 1, 2, 3, 4]
squared = [x**2 for x in arr if x % 2 == 0]  # Even squares
flat = [item for sublist in nested for item in sublist]  # Flatten 2D list

# Slicing
arr[1:3]                # Elements 1 and 2
arr[::-1]               # Reverse array
arr[::2]                # Every other element

Dictionaries (Hash Maps)

# Creation and operations
myMap = {}
myMap["alice"] = 88
myMap["bob"] = 77
myMap.update({"charlie": 90, "david": 85})  # Add multiple items

# Accessing and checking
value = myMap.get("alice", "default")  # Get with default
"alice" in myMap        # Check if key exists
keys = myMap.keys()     # Get all keys
values = myMap.values() # Get all values
items = myMap.items()   # Get all key-value pairs

# Removing elements
age = myMap.pop("alice")          # Remove and return value
removed_item = myMap.popitem()     # Remove and return last item
del myMap["bob"]                   # Remove key
myMap.clear()                      # Remove all items

# Dictionary operations
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged = {**dict1, **dict2}       # Merge dictionaries
swapped = {v: k for k, v in dict1.items()}  # Swap keys/values

# SetDefault
myMap.setdefault("key", "default")  # Get existing or set default

# Copy dictionary
copied = myMap.copy()              # Shallow copy

# Dict comprehension
myMap = {i: i**2 for i in range(3)}  # {0: 0, 1: 1, 2: 4}
filtered = {k: v for k, v in myMap.items() if v > 1}

# Unpacking
# * unpacks a list
# ** unpacts a dictionary

# Fucnctional unpacking
def add(a, b):
    return a + b
values = [5, 3]
result = add(*values)  # Unpacking the list into the arguments of add
print(f"Result of addition: {result}")  # Output: Result of addition: 8

def greet(greeting, name):
    print(f"{greeting}, {name}!")

info = ("Hello", "Alice")
greet(*info)  # Unpacking the tuple into the arguments of greet
# Output: Hello, Alice!

Sets (Hash Sets)

# Creation and operations
mySet = set()
mySet.add(1)
mySet.remove(1)         # Raises KeyError if not present
mySet.discard(1)        # No error if not present

# Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union = set1 | set2     # Or: set1.union(set2)
intersection = set1 & set2  # Or: set1.intersection(set2)
difference = set1 - set2    # Or: set1.difference(set2)

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

Tuples (Immutable Lists)

# Creation and access
tup = (1, 2, 3)
first = tup[0]
last = tup[-1]

# Can be used as dictionary keys
myMap = {(1, 2): 3}

Heaps

import heapq

# Min heap
minHeap = []
heapq.heappush(minHeap, 3)
heapq.heappush(minHeap, 2)
minValue = heapq.heappop(minHeap)

# Max heap (negate values)
maxHeap = []
heapq.heappush(maxHeap, -3)
maxValue = -1 * heapq.heappop(maxHeap)

# Heapify array
arr = [2, 1, 8, 4, 5]
heapq.heapify(arr)

Queues