Although Python interviews vary from company to company, they draw from a surprisingly recurring pool of core questions. Interviewers generally want to measure three things:

  1. Do you truly understand the language? (Not just using syntax, but understanding what happens under the hood)
  2. Can you solve problems? (Algorithms and data structures)
  3. Can you write production-grade code safely? (Performance, concurrency, readability, edge cases)

In this comprehensive guide, we cover the most frequently asked technical Python interview questions by experience level, explaining each with working code examples. At the end, you will also find live coding challenges, a Big-O complexity cheat sheet, and practical tips for interview day.


1. Fundamental Level Questions

1.1 What is the difference between mutable and immutable types?

This is the opening question of almost every Python interview.

  • Immutable (cannot be modified in-place): int, float, bool, str, tuple, frozenset, bytes
  • Mutable (can be modified in-place): list, dict, set, bytearray, most user-defined classes
name = "python"
# name[0] = "P"         # TypeError: 'str' object does not support item assignment
name = "P" + name[1:]   # Creates a brand-new string object in memory

numbers = [1, 2, 3]
numbers[0] = 99         # Mutates the existing list object in-place
print(numbers)          # [99, 2, 3]

Detail that will impress the interviewer: An immutable tuple can hold a reference to a mutable object inside it.

t = ([1, 2], 3)
t[0].append(3)
print(t)  # ([1, 2, 3], 3)  -> The tuple references didn't change, the inner list mutated

Because of this, such a tuple is not hashable (TypeError: unhashable type: 'list') and cannot be used as a dict key or set element.


1.2 What are the differences between list and tuple?

Feature list tuple
Mutability Mutable Immutable
Syntax [1, 2, 3] (1, 2, 3)
Hashable No Yes (if all contained elements are hashable)
Can be a dict key? No Yes (when hashable)
Memory footprint Higher (over-allocates for dynamic growth) Lower (fixed size allocation)
Typical use case Homogeneous collections that grow/shrink Fixed-structure records (coordinates, DB rows, RGB)

1.3 What is the difference between is and ==?

  • == → Value equality (invokes the __eq__ method)
  • is → Identity equality (checks whether two variables point to the exact same object in memory: id(a) == id(b))
a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a == b)  # True  -> Values are equal
print(a is b)  # False -> Distinct list objects in memory
print(a is c)  # True  -> Both point to the exact same object

Golden rule: Always use is when comparing against singletons like None, True, and False: if x is None:.

In CPython, small integers between -5 and 256 are interned (cached), so a = 256; b = 256; a is b evaluates to True. However, this is a CPython implementation detail—never rely on is for value comparison of integers or strings.


1.4 Why is using a mutable object as a default argument dangerous?

This is one of Python's most famous pitfalls.

def append_item(item, target=[]):
    target.append(item)
    return target

print(append_item(1))  # [1]
print(append_item(2))  # [1, 2]  -> Expected [2], got [1, 2]!

Why? Default argument values are evaluated once when the function is defined (def), not each time the function is called. Every call that omits target shares the exact same list object stored in append_item.__defaults__.

Correct idiom:

def append_item(item, target=None):
    if target is None:
        target = []
    target.append(item)
    return target

1.5 What are *args and **kwargs?

  • *args → Collects a variable number of positional arguments into a tuple.
  • **kwargs → Collects a variable number of keyword arguments into a dict.
def inspect_call(*args, **kwargs):
    print("args:", args)
    print("kwargs:", kwargs)

inspect_call(1, 2, 3, name="Ada", age=30)
# args: (1, 2, 3)
# kwargs: {'name': 'Ada', 'age': 30}

They also work in reverse when calling functions (argument unpacking):

def add(a, b, c):
    return a + b + c

numbers = [1, 2, 3]
config = {"a": 1, "b": 2, "c": 3}

print(add(*numbers))   # 6
print(add(**config))   # 6

1.6 What is the difference between shallow copy and deep copy?

import copy

original = [[1, 2], [3, 4]]
shallow  = copy.copy(original)      # Copies only the outer container
deep     = copy.deepcopy(original)  # Recursively copies all nested objects

original[0].append(99)

print(shallow)  # [[1, 2, 99], [3, 4]]  -> Inner lists are still shared!
print(deep)     # [[1, 2], [3, 4]]      -> Completely independent
  • Shallow copy: Creates a new outer container, but populates it with references to the same inner objects (list.copy(), lst[:], and dict.copy() all perform shallow copies).
  • Deep copy: Recursively clones the outer container and every nested object inside it.

1.7 What is a list comprehension, and when should you avoid it?

# Classic loop
squares = []
for x in range(10):
    if x % 2 == 0:
        squares.append(x ** 2)

# List comprehension
squares = [x ** 2 for x in range(10) if x % 2 == 0]

# Dict and set comprehensions
square_map = {x: x ** 2 for x in range(5)}      # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
unique_chars = {c.lower() for c in "InTerView"} # {'i', 'n', 't', 'e', 'r', 'v', 'w'}

# Generator expression (memory-friendly lazy evaluation)
total = sum(x ** 2 for x in range(1_000_000))

When should you avoid it? Avoid comprehensions when nesting exceeds 2 levels, when the logic becomes hard to read at a glance, or when you only want side effects (e.g., calling print()). Readability always comes first.

🎯 Interactive Practice Problems for Fundamentals

2. Intermediate Level Questions

2.1 What is a decorator? Can you write your own decorator?

A decorator is a higher-order function that takes a function and extends its behavior without modifying its source code. In interviews, you are frequently asked to "write a decorator that measures a function's execution time."

import functools
import time

def timer(func):
    @functools.wraps(func)  # Preserves the original function's __name__ and __doc__
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        elapsed = time.perf_counter() - start
        print(f"{func.__name__} took {elapsed:.4f}s")
        return result
    return wrapper

@timer
def slow_operation():
    time.sleep(1)
    return "done"

slow_operation()  # slow_operation took 1.0012s

Follow-up question: Can you write a decorator that accepts arguments? This requires one additional outer factory function:

def repeat(n):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            result = None
            for _ in range(n):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(3)
def greet():
    print("Hello!")

greet()  # Prints "Hello!" 3 times

Forgetting @functools.wraps(func) is a classic detail interviewers watch for, because without it, debugging, introspection, and docstrings break.


2.2 What is a generator, and what does yield do?

A generator is an iterator that produces values lazily—one at a time and only on demand. While return terminates a function completely, yield suspends the function's execution state (local variables and instruction pointer) and resumes from the exact same spot on the next next() call.

def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

gen = fibonacci()
print([next(gen) for _ in range(10)])  # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Why does it matter? Memory efficiency:

import sys

eager_list = [x for x in range(1_000_000)]
lazy_gen   = (x for x in range(1_000_000))

print(sys.getsizeof(eager_list))  # ~8 MB
print(sys.getsizeof(lazy_gen))    # ~200 bytes

Generators are indispensable when reading multi-gigabyte log files line by line or building streaming data pipelines.


2.3 What is the difference between an iterable and an iterator?

  • Iterable: Any object you can loop over. It implements __iter__() (or __getitem__()). Examples: list, str, dict, range.
  • Iterator: A stateful object that produces the next value in a sequence. It implements both __iter__() (returning self) and __next__() (raising StopIteration when exhausted).
class Countdown:
    def __init__(self, start):
        self.current = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.current <= 0:
            raise StopIteration
        self.current -= 1
        return self.current + 1

for num in Countdown(3):
    print(num)  # 3, 2, 1

Every iterator is an iterable, but not every iterable is an iterator. Calling iter([1, 2, 3]) creates a list_iterator from a list.


2.4 What is a context manager, and how does the with statement work?

A context manager guarantees that resources (files, network sockets, database transactions, locks) are safely acquired and deterministically released, even if an exception occurs inside the block.

with open("data.txt", "r", encoding="utf-8") as f:
    content = f.read()
# The file is guaranteed to be closed here

Writing a class-based context manager:

import time

class Stopwatch:
    def __enter__(self):
        self.start = time.perf_counter()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        elapsed = time.perf_counter() - self.start
        print(f"Elapsed: {elapsed:.4f}s")
        return False  # Do not suppress exceptions; let them propagate

Writing a generator-based context manager with contextlib:

import os
from contextlib import contextmanager

@contextmanager
def working_directory(path):
    prev_dir = os.getcwd()
    os.chdir(path)
    try:
        yield
    finally:
        os.chdir(prev_dir)

2.5 What is the GIL (Global Interpreter Lock)?

This is a near-certain question in mid-level and senior interviews.

The GIL is a mutex in the standard CPython interpreter that allows only one OS thread to execute Python bytecode at a time. It exists primarily to keep CPython's reference-counting memory management fast and thread-safe without needing fine-grained locks on every Python object.

Practical consequences:

  • In CPU-bound workloads (matrix math, image processing, cryptographic hashing), threading does not achieve parallel speedup across CPU cores. Use multiprocessing or C/Rust extensions (NumPy, Polars) that release the GIL.
  • In I/O-bound workloads (HTTP requests, disk I/O, database queries), CPython releases the GIL while waiting for OS I/O, making threading and asyncio highly effective.

Up-to-date bonus point: Mention PEP 703 (Free-Threaded CPython). Experimental free-threaded builds (python3.13t / python3.14t) allow running Python without the GIL, and PEP 779 moved free-threaded Python onto a supported track, though standard GIL-enabled builds remain the default while the ecosystem adapts.


2.6 What are the differences between threading, multiprocessing, and asyncio?

Dimension threading multiprocessing asyncio
Execution model Multiple OS threads Multiple OS processes Single thread, cooperative event loop
Affected by the GIL? Yes No (each process has its own interpreter & GIL) N/A (single-threaded)
Best workload Blocking I/O-bound tasks CPU-bound parallel computation High-concurrency network/I/O (10k+ connections)
Memory model Shared memory space Isolated memory (requires IPC / queues) Shared memory space
Overhead Low High (process spawning & serialization) Very low (lightweight coroutines)
import asyncio

async def fetch_data(item_id: int) -> str:
    await asyncio.sleep(1)  # Simulates non-blocking network I/O
    return f"payload-{item_id}"

async def main():
    results = await asyncio.gather(*(fetch_data(i) for i in range(5)))
    print(results)  # Fetches all 5 in ~1 second total (not 5 seconds!)

asyncio.run(main())

2.7 What is the difference between @staticmethod, @classmethod, and an instance method?

class DateRecord:
    def __init__(self, day: int, month: int, year: int):
        self.day, self.month, self.year = day, month, year

    # Instance method: receives the instance (self)
    def format_iso(self) -> str:
        return f"{self.year:04d}-{self.month:02d}-{self.day:02d}"

    # Class method: receives the class (cls); ideal for alternative constructors
    @classmethod
    def from_string(cls, text: str):
        day, month, year = map(int, text.split("."))
        return cls(day, month, year)

    # Static method: receives neither self nor cls; utility namespace helper
    @staticmethod
    def is_leap_year(year: int) -> bool:
        return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

d = DateRecord.from_string("18.10.2026")
print(d.format_iso())                 # 2026-10-18
print(DateRecord.is_leap_year(2024))  # True

Because @classmethod receives cls, calling from_string on a subclass automatically instantiates that subclass—which is why @classmethod is preferred over @staticmethod for factory methods.


2.8 What is the LEGB rule, and what do global and nonlocal do?

Python resolves variable names in the following scope order:

  1. Local – Inside the current function
  2. Enclosing – Inside any enclosing outer functions
  3. Global – Module-level namespace
  4. Built-in – Python's builtins module (len, print, Exception, etc.)
def make_counter():
    count = 0
    def increment():
        nonlocal count   # Rebinds the variable in the Enclosing scope
        count += 1
        return count
    return increment

counter = make_counter()
print(counter(), counter(), counter())  # 1 2 3

This is also a textbook closure: increment retains access to count even after make_counter() has finished executing.


2.9 What are dunder (magic) methods, and how do __str__ and __repr__ differ?

Double-underscore ("dunder") methods let your custom objects integrate with Python's built-in syntax and operators (arithmetic, iteration, comparisons, context management).

class Vector2D:
    def __init__(self, x: float, y: float):
        self.x, self.y = x, y

    def __repr__(self) -> str:  # Unambiguous representation for developers / debugging
        return f"Vector2D({self.x!r}, {self.y!r})"

    def __str__(self) -> str:   # Readable representation for end users / print()
        return f"({self.x}, {self.y})"

    def __add__(self, other: "Vector2D") -> "Vector2D":
        return Vector2D(self.x + other.x, self.y + other.y)

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Vector2D):
            return NotImplemented
        return (self.x, self.y) == (other.x, other.y)

v = Vector2D(1, 2) + Vector2D(3, 4)
print(v)        # (4, 6)
print(repr(v))  # Vector2D(4, 6)

A good __repr__ should ideally look like a valid Python expression that could recreate the object (eval(repr(obj)) == obj). If __str__ is not defined, Python falls back to __repr__.


2.10 What is Multiple Inheritance and MRO (Method Resolution Order)?

class A:
    def who(self): return "A"

class B(A):
    def who(self): return "B"

class C(A):
    def who(self): return "C"

class D(B, C):
    pass

print(D().who())                        # B
print([cls.__name__ for cls in D.__mro__])  # ['D', 'B', 'C', 'A', 'object']

Python computes the MRO using the C3 linearization algorithm. This resolves the classic "diamond inheritance problem" and ensures that cooperative super() calls visit each ancestor class exactly once in a deterministic order.

🎯 Interactive Practice Problems for Intermediate Level

3. Advanced Level Questions

3.1 How does memory management work in Python?

CPython combines two complementary mechanisms:

  1. Reference counting: Every object header (PyObject) tracks how many references point to it (ob_refcnt). The moment the count drops to zero, the memory is reclaimed immediately and deterministically.
  2. Generational cyclic garbage collector (gc): Reference counting alone cannot free reference cycles (where object A references B and B references A, with no external references). The cyclic GC periodically scans container objects across three generations (0, 1, 2) to detect and break unreachable cycles.
import sys

a = []
print(sys.getrefcount(a))  # 2 (variable 'a' + temporary argument passed to getrefcount)

b = a
print(sys.getrefcount(a))  # 3
# Reference cycle that reference counting alone cannot free
class Node:
    def __init__(self):
        self.peer = None

x, y = Node(), Node()
x.peer, y.peer = y, x   # Cycle created
del x, y                # Refcounts remain 1 -> cleaned up by the cyclic 'gc' module

3.2 What is __slots__, and when should you use it?

By default, every Python instance stores its attributes in a dynamic per-instance dictionary (__dict__). Declaring __slots__ instructs Python to allocate a fixed-size C array of attribute pointers instead of creating __dict__:

class Point:
    __slots__ = ("x", "y")

    def __init__(self, x: float, y: float):
        self.x, self.y = x, y

p = Point(1.0, 2.0)
# p.z = 3.0  # AttributeError: 'Point' object has no attribute 'z'
  • Benefits: Reduces per-instance memory usage by 40–60% and slightly speeds up attribute access. Crucial when instantiating millions of value objects (e.g., AST nodes, graph vertices, financial ticks).
  • Trade-offs: Cannot dynamically attach arbitrary new attributes at runtime, and requires care with multiple inheritance.

3.3 What is a metaclass?

"Classes create instances; metaclasses create classes."

In Python, classes themselves are objects—specifically, instances of their metaclass (which defaults to type). Interviewers often ask for a Singleton or class-registration example:

class SingletonMeta(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super().__call__(*args, **kwargs)
        return cls._instances[cls]

class AppConfig(metaclass=SingletonMeta):
    pass

print(AppConfig() is AppConfig())  # True

Senior-level nuance: Mentioning that "Metaclasses are powerful, but in 95% of cases __init_subclass__, class decorators, or a simple module-level singleton are cleaner and easier to maintain" shows real engineering maturity.


3.4 What is a dataclass, and how does it differ from a regular class?

from dataclasses import dataclass, field

@dataclass(frozen=True, slots=True)
class Employee:
    name: str
    salary: float
    skills: list[str] = field(default_factory=list)

emp = Employee("Ada", 95_000)
print(emp)  # Employee(name='Ada', salary=95000, skills=[])

@dataclass automatically generates __init__, __repr__, and __eq__ based on type annotations. Passing frozen=True makes instances immutable (and hashable), slots=True (Python 3.10+) generates __slots__, and field(default_factory=list) safely avoids the mutable default argument trap!

🎯 Interactive Problems for Advanced Python & System Design

4. "Guess the Output" Trick Questions

Interviewers love these snippets to test whether you understand how Python actually executes code. Try predicting each output before opening the answer!

Puzzle 1: List multiplication

x = [[0] * 3] * 3
x[0][0] = 1
print(x)
Answer
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

The outer * 3 does not clone the inner list—it creates three references to the exact same inner list. Correct way: x = [[0] * 3 for _ in range(3)].

Puzzle 2: Lambdas and late binding in closures

funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])
Answer
[2, 2, 2]

Closures capture variables by reference, not their current value at creation time. By the time the lambdas are called, the loop has finished and i is 2. Fix by binding a default argument: funcs = [lambda i=i: i for i in range(3)].

Puzzle 3: Single-element tuple syntax

a = (1)
b = (1,)
print(type(a), type(b))
Answer
<class 'int'> <class 'tuple'>

It is the trailing comma, not the parentheses, that constructs a tuple. (1) is just a parenthesized integer expression.

Puzzle 4: Floating-point precision

print(0.1 + 0.2 == 0.3)
Answer
False

IEEE 754 binary floating-point numbers cannot represent 0.1 and 0.2 exactly (0.1 + 0.2 == 0.30000000000000004). Use math.isclose(0.1 + 0.2, 0.3) for float comparisons, or decimal.Decimal for financial calculations.

Puzzle 5: try / finally with return

def f():
    try:
        return "try"
    finally:
        return "finally"

print(f())
Answer
finally

The finally block always executes before the function exits, so its return overrides the return from try (and even swallows unhandled exceptions!). Because this behavior is a notorious source of bugs, Python 3.14+ emits a SyntaxWarning when return, break, or continue appears inside finally (PEP 765).

Puzzle 6: Boolean arithmetic

print(True + True + False)
print(isinstance(True, int))
Answer
2
True

In Python, bool is a subclass of int (issubclass(bool, int) is True), where True == 1 and False == 0. That also lets you count truthy items concisely: sum(x > 0 for x in nums).

🎯 Algorithmic Edge Cases & Trick Practice

5. Live Coding Interview Classics

During live coding, interviewers evaluate not just whether your code works, but how you communicate your thought process and whether you write idiomatic (Pythonic) code.

5.1 Valid Palindrome Check

def is_palindrome(text: str) -> bool:
    cleaned = "".join(c.lower() for c in text if c.isalnum())
    return cleaned == cleaned[::-1]

print(is_palindrome("A man, a plan, a canal: Panama"))  # True

💡 Solve Interactively: To solve this in O(1) extra memory using the two-pointers technique without allocating a reversed copy, test your code in the studio: K11: Valid Palindrome

5.2 Anagram Check

from collections import Counter

def is_anagram(a: str, b: str) -> bool:
    return Counter(a.replace(" ", "").lower()) == Counter(b.replace(" ", "").lower())

print(is_anagram("Listen", "Silent"))  # True

💡 Solve Interactively: Practice the classic follow-up variation that groups a list of words by character frequency signature: O15: Group Anagrams

5.3 Two Sum (O(n) Hash Map Solution)

Given an array of integers and a target sum, return the indices of the two elements that add up to the target.

def two_sum(nums: list[int], target: int) -> list[int]:
    seen = {}  # value -> index
    for i, num in enumerate(nums):
        complement = target - num
        if complement in seen:
            return [seen[complement], i]
        seen[num] = i
    return []

print(two_sum([2, 7, 11, 15], 9))  # [0, 1]

Briefly stating the naive O(n²) nested-loop approach first and then optimizing to O(n) time with a dictionary lookup is the exact progression interviewers love to see.

💡 Solve Interactively: When the input array is already sorted, solve it in O(1) auxiliary space using two pointers: K12: Two Sum II - Sorted Array

5.4 Deduplicating a List While Preserving Order

def dedup_preserve_order(items: list) -> list:
    return list(dict.fromkeys(items))

print(dedup_preserve_order([3, 1, 3, 2, 1]))  # [3, 1, 2]

list(set(items)) does not preserve insertion order. Since Python 3.7+, dict is guaranteed by the language spec to preserve insertion order.

💡 Solve Interactively: Removing duplicates in-place from a sorted list in O(1) extra space is a staple live coding question: K13: Remove Duplicates from Sorted Array

5.5 Top K Most Frequent Elements

from collections import Counter

words = "apple pear apple cherry apple pear".split()
print(Counter(words).most_common(2))  # [('apple', 3), ('pear', 2)]

5.6 Flattening an Arbitrarily Nested List

def flatten(nested):
    for item in nested:
        if isinstance(item, list):
            yield from flatten(item)
        else:
            yield item

print(list(flatten([1, [2, [3, 4]], 5])))  # [1, 2, 3, 4, 5]

5.7 Memoized Fibonacci with lru_cache

from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n: int) -> int:
    return n if n < 2 else fib(n - 1) + fib(n - 2)

print(fib(100))  # 354224848179261915075

Unmemoized recursion takes exponential O(2ⁿ) time, whereas @lru_cache reduces it to linear O(n) time.

🎯 Most Asked Live Coding Interview Algorithms

6. Time Complexity (Big-O) Cheat Sheet

Interviewers almost always ask: "What is the time and space complexity of your solution?" Knowing the cost of Python's built-in container operations is essential:

Operation list dict / set collections.deque
Append to right (append / add) O(1)* O(1)* O(1)
Prepend to left (insert(0, x) / appendleft) O(n) — O(1)
Index access (seq[i]) O(1) — O(n)
Key lookup (d[k]) — O(1)* —
Membership check (x in ...) O(n) O(1)* O(n)
Pop from right (pop()) O(1) — O(1)
Pop from left (pop(0) / popleft()) O(n) O(1)* O(1)
Sorting (sort()) O(n log n) — —

* Average / amortized complexity.

Pro tip: If you are repeatedly checking if x in items: inside a loop, converting items from a list to a set turns an O(n²) bottleneck into O(n). And if you need a FIFO queue with fast pops from the front, never use list.pop(0)—always use collections.deque.popleft().

🎯 Interactive Problems for Big-O Optimization

7. Practical Tips for Interview Day

  1. Think out loud. Instead of coding in silence for 10 minutes, narrate your reasoning. If you head down a dead end, the interviewer can course-correct you early.
  2. Clarify constraints first. Can the input be empty? Are there negative numbers or duplicates? Does it fit in memory? Asking clarifying questions demonstrates engineering maturity.
  3. Make it work, then make it fast. State the brute-force solution and its Big-O complexity in 30 seconds, then explain how to optimize it with the right data structure.
  4. Write Pythonic code. Prefer enumerate() over range(len(arr)), zip() for parallel iteration, Counter / defaultdict over manual dictionary key checks, and with for resource management.
  5. Trace boundary cases. Dry-run your code against an empty list [], a single element [x], all identical elements, and negative inputs before saying "I'm done."
  6. Know the standard library batteries. collections (Counter, defaultdict, deque), itertools, functools (lru_cache), heapq, and bisect save huge amounts of time in interviews.
  7. Be honest when you don't know a detail. Saying "I don't recall the exact method name, but under the hood it works like this..." is always better than guessing blindly.

Final Pre-Interview Checklist ✅

Make sure you can clearly explain each of these topics before walking into your interview:

  • Mutable vs. immutable types and hashability rules
  • is (identity) vs. == (value equality)
  • The mutable default argument pitfall (def f(x=[]))
  • Shallow copy vs. deep copy
  • Writing decorators (including parameterized decorators and @functools.wraps)
  • Generators, yield, and the iterator protocol (__iter__ / __next__)
  • Context managers (__enter__ / __exit__ and @contextmanager)
  • The GIL and choosing between threading, multiprocessing, and asyncio
  • @staticmethod vs. @classmethod vs. instance methods
  • LEGB scope resolution, closures, and nonlocal
  • Dunder methods (__repr__ vs. __str__) and C3 MRO
  • Reference counting, cyclic garbage collection, and __slots__
  • Big-O time complexities of list, dict, set, and deque

Conclusion

Python technical interviews reward deep understanding over rote memorization. Don't just passively read the code snippets in this guide—run them, tweak them, and test their edge cases. Once you can explain a concept simply to another developer, you are ready to ace it in an interview.

To put theory into immediate practice, explore our 200-Problem Interview Catalog and 10 Specialization Modules directly in your browser, or jump straight into your first interactive challenge: K01: Packages Above Average. Good luck! 🐍

Interactive Practice Station

Ready to Test Theory in a Real Exam Environment?

10 specialization modules and 200 original Python interview problems await you on PyMülakat. Write and run your code in the browser and test yourself against hidden boundary cases.

Solve First Problem (K01) →Explore Modules