Ad – 728Γ—90
πŸ“ Interview Prep

Python Interview Exercises

These exercises cover OOP design, built-in data structures, generators, and functional patterns β€” concepts commonly tested in Python interviews.

⏱️ 20 min read🎯 Interview PrepπŸ“… Updated 2026

Exercise 1 – Cache Decorator

Python
def cache(func):
    memo = {}
    def wrapper(*args):
        if args not in memo:
            memo[args] = func(*args)
        return memo[args]
    return wrapper

@cache
def expensive(n):
    print(f"Computing {n}...")
    return n * n

expensive(5)  # Computing 5... β†’ 25
expensive(5)  # from cache β†’ 25

Exercise 2 – Stack Class

Python
class Stack:
    def __init__(self):
        self._items = []

    def push(self, item): self._items.append(item)

    def pop(self):
        if not self._items:
            raise IndexError("Stack is empty")
        return self._items.pop()

    def peek(self):
        if not self._items:
            raise IndexError("Stack is empty")
        return self._items[-1]

    def __len__(self): return len(self._items)
    def __bool__(self): return bool(self._items)

s = Stack()
s.push(1); s.push(2); s.push(3)
print(s.peek())  # 3
print(s.pop())   # 3

Exercise 3 – Infinite Counter Generator

Python
def counter(start=0, step=1):
    n = start
    while True:
        yield n
        n += step

import itertools
evens = list(itertools.islice(counter(0, 2), 5))
print(evens)  # [0, 2, 4, 6, 8]

Exercise 4 – Timer Context Manager

Python
import time
from contextlib import contextmanager

@contextmanager
def timer(label=""):
    start = time.perf_counter()
    try:
        yield
    finally:
        elapsed = time.perf_counter() - start
        print(f"{label}: {elapsed:.4f}s")

with timer("List comp"):
    result = [x**2 for x in range(1_000_000)]

Exercise 5 – Flatten Nested List

Python
from collections.abc import Iterable

def flatten(iterable):
    for item in iterable:
        if isinstance(item, Iterable) and not isinstance(item, str):
            yield from flatten(item)
        else:
            yield item

nested = [1, [2, [3, 4]], [5, 6], 7]
print(list(flatten(nested)))  # [1, 2, 3, 4, 5, 6, 7]
Tip: In interviews: clarify requirements first, discuss time/space complexity, then handle edge cases before declaring done.