Interview Prep/Python

Top 50 Python Interview Questions & Answers 2025

Master Python interviews with 50+ essential questions on data structures, OOP, decorators, and real-world problem solving.

19 Questions~30 min read6 CategoriesUpdated 2025
Practice Python Quiz

Data Structures

01 · 4q

Lists are mutable (can be modified after creation) and use square brackets []. Tuples are immutable (cannot be changed) and use parentheses (). Tuples are faster, can be used as dictionary keys, and are preferred for fixed collections. Lists are better when you need to modify the collection.

Shallow copy (copy.copy) creates a new object but references nested objects from the original. Deep copy (copy.deepcopy) creates a new object and recursively copies all nested objects. Use deep copy when you need completely independent copies of nested structures; shallow copy when nested objects should be shared.

List comprehension [x for x in range(10)] creates a full list in memory. Generator expression (x for x in range(10)) creates an iterator that yields values on demand. Use list comprehension when you need the full list; use generator expressions for large sequences or when you only need to iterate once.

[x for x in items if cond] — list comprehension, creates full list. {k: v for k, v in items} — dict comprehension. {x for x in items} — set comprehension (unique values). (x for x in items) — generator expression, lazy. All support filtering with if clause and nested loops. Prefer comprehensions over map/filter for readability. Use generators for large datasets.

Functions

02 · 4q

Decorators are functions that modify the behavior of other functions without changing their code. They use the @decorator syntax. Example use cases: logging, timing, authentication, caching. A decorator takes a function, wraps it with additional functionality, and returns the wrapper. Common built-in decorators: @property, @staticmethod, @classmethod.

*args allows a function to accept any number of positional arguments as a tuple. **kwargs allows any number of keyword arguments as a dictionary. They enable flexible function signatures. Convention: use these names, though any name with * or ** works. Often used in decorators, class inheritance, and wrapper functions.

Generators are functions that use yield instead of return, producing values lazily one at a time. Benefits: memory efficiency (don't load entire sequence into memory), represent infinite sequences, simpler code than implementing iterators. Use for large datasets, streaming data, or when you don't need all values at once.

map(func, iterable): applies func to each element, returns iterator. filter(func, iterable): keeps elements where func is True. reduce(func, iterable): accumulates (from functools). zip: pairs elements from multiple iterables. sorted with key param. all/any for boolean aggregation. functools.partial for partial application. itertools for efficient iteration: chain, product, combinations.

Concurrency

03 · 3q

The GIL is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecode simultaneously. This limits true parallelism for CPU-bound tasks in CPython. Solutions: use multiprocessing for CPU-bound work, asyncio for I/O-bound work, or consider PyPy or Cython. The GIL doesn't affect I/O operations.

asyncio is Python's async I/O framework using an event loop. async def defines coroutines; await suspends execution until the awaited coroutine completes. asyncio.gather runs coroutines concurrently. asyncio.create_task schedules coroutines. Use for I/O-bound concurrency (HTTP, database). Not for CPU-bound work — use multiprocessing. Libraries: aiohttp, asyncpg, FastAPI.

Use threading.Lock for mutual exclusion. threading.RLock for reentrant locks. Queue.Queue for thread-safe producer-consumer. threading.Event and Condition for synchronization. The GIL protects CPython internals but not compound operations (check-then-act). Use concurrent.futures.ThreadPoolExecutor for managed thread pools. For CPU-bound parallelism, use multiprocessing.

OOP

04 · 4q

@staticmethod defines a method that doesn't access instance or class state - it's like a regular function in the class namespace. @classmethod receives the class (cls) as first argument and can access/modify class state. Use staticmethod for utility functions, classmethod for factory methods or operations on class attributes.

Duck typing means Python checks an object's methods/attributes rather than its type. "If it walks like a duck and quacks like a duck, it's a duck." This enables polymorphism without inheritance. Example: any object with a __len__ method works with len(). It promotes flexible, reusable code but requires good documentation.

@dataclass (Python 3.7+) auto-generates __init__, __repr__, __eq__ from type-annotated fields. Options: frozen (immutable), order (comparison), slots (memory efficient). Better than namedtuple for mutable data. Use field() for defaults, post_init for initialization logic. Pydantic extends data classes with runtime validation — essential for API development.

Python supports multiple inheritance. Method Resolution Order (MRO) determines which method is called using C3 linearization algorithm. Access via ClassName.__mro__ or mro(). super() follows MRO order, enabling cooperative multiple inheritance. Common pattern: mixin classes that add specific behaviors without being standalone. Diamond problem is resolved by MRO.

Internals

05 · 2q

Python uses reference counting as primary memory management - objects are freed when reference count reaches zero. It also has a generational garbage collector to handle circular references. Memory is managed by a private heap. The memory manager handles allocation; you rarely interact with it directly but should avoid circular references and use context managers.

Metaclasses are "classes of classes" — they control class creation. When Python creates a class, it calls the metaclass (default: type). Custom metaclass: inherit from type, override __new__ or __init__. Use for: ORMs (Django models), API framework magic (Flask routes), enforcing interface contracts, singletons. Usually overkill; prefer class decorators or __init_subclass__ for simpler cases.

Core Concepts

06 · 2q

Context managers handle setup/teardown automatically via __enter__ and __exit__ methods. The with statement calls these around a block, guaranteeing cleanup even on exceptions. Create with class (implement __enter__/__exit__) or @contextlib.contextmanager decorator with yield. Common uses: file handling, database connections, locks, temporary state changes.

Key changes: print is a function (not statement), integer division returns float (3/2 = 1.5), strings are Unicode by default, range() returns iterator (not list), input() replaces raw_input(), dict methods return views not lists. Python 2 EOL was 2020 — all new code should use Python 3. Most libraries dropped Python 2 support.

Related Topics

Ready to test your Python skills?

Practice with interactive quizzes and get instant feedback.

Start Free Practice