Skip to main content

Learning Resources

Top 100 Interview Q&A

The Top 100 Python interview questions and answers, covering every major area of the language — from basics and OOP to data structures, exceptions, generators, decorators, and the standard library.

Top 100 Questions

Python Interview Questions & Answers

The most frequently asked Python interview questions, covering every major area of the language — basics and typing, strings, collections, functions, OOP, exceptions, generators and decorators, modules, concurrency (GIL, threads, asyncio), and coding/output puzzles. Each answer is written the way you should say it in an interview.

Python Basics & Language

Q1–Q10

Q1 What is Python and what makes it popular for interviews?

Answer Python is a high-level, dynamically typed, interpreted language with significant indentation, a large standard library, and a clear object model (everything is an object). Interviewers value readable syntax, duck typing, and the ability to explain CPython’s GIL, mutability, and common data structures.

Q2 Interpreted vs compiled — how does Python run?

Answer CPython compiles source to bytecode (.pyc / __pycache__) then interprets that bytecode on a virtual machine. Other implementations (PyPy, Jython, IronPython) differ. “Interpreted” is the usual interview shorthand; bytecode + VM is the accurate CPython picture.

Q3 What is PEP 8?

Answer The style guide for Python code: indentation (4 spaces), naming (snake_case functions, CapWords classes), imports, line length guidance, and blank-line conventions. Interviews rarely quiz every rule, but clean PEP-8-ish code signals professionalism.

Q4 What are *args and **kwargs?

Answer *args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. In a call, * unpacks an iterable into positionals and ** unpacks a mapping into keywords. Order in a def is: plain params, *args, keyword-only, **kwargs.

Q5 What is the difference between is and ==?

Answer == calls __eq__ and tests value equality. is tests object identity (same object in memory). Use is for None (x is None), True/False in some style guides, and singletons — not for comparing ints/strings by value (small-int interning can make is “accidentally” true).

Q6 Mutable vs immutable types?

Answer Immutable: int, float, bool, str, tuple, frozenset, bytes — “change” creates a new object. Mutable: list, dict, set, bytearray, most user objects — in-place updates. Mutability affects default arguments, hashing, and thread-safety assumptions.

Q7 Why are mutable default arguments a bug?

Answer Defaults are evaluated once at function definition. A default list/dict/set is shared across calls, so appends/mutations accumulate. Use None as the default and create a new container inside the function.

Q8 What does pass do?

Answer A no-op statement used where syntax requires a body (empty class/function, stub branch). Prefer ... (Ellipsis) or raise NotImplementedError for unfinished APIs when that intent matters.

Q9 How does indentation work in Python?

Answer Blocks are defined by consistent indentation, not braces. Mixing tabs and spaces raises TabError. Official style is 4 spaces. Suites after :, and a dedent ends the block.

Q10 What is the Python Zen (import this)?

Answer Tim Peters’ guiding aphorisms: readability counts, explicit is better than implicit, simple is better than complex, there should be one obvious way, etc. Useful culture signal in interviews, not a language feature.

Types, Typing & Objects

Q11–Q19

Q11 What does dynamically typed mean?

Answer Names are bound to objects at runtime; the type lives on the object, not the variable. You can rebind x from an int to a str. Static checkers (mypy) and annotations (PEP 484) add optional static analysis without changing runtime behaviour by default.

Q12 What are type hints (Python 3.10+)?

Answer Annotations like def f(x: int) -> str: document and enable tools. 3.10+ prefers X | Y over Optional/Union for unions, and list[int], dict[str, int] built-in generics (from __future__ import annotations or 3.9+). Hints are not enforced by CPython unless you use a checker or runtime validation library.

Q13 id(), type(), and isinstance()?

Answer id(obj) returns an identity (CPython: memory address-like int). type(obj) returns the exact class. isinstance(obj, cls) (or a tuple of types) is preferred for checks because it respects inheritance and ABCs; type(obj) is cls does not.

Q14 What is None?

Answer The singleton null object (NoneType). Compare with is None / is not None. It is falsy. Functions without an explicit return return None.

Q15 Truthy and falsy values?

Answer Falsy: False, None, 0, 0.0, 0j, empty str/list/dict/set/tuple/range, and objects whose __bool__ or __len__ says so. Everything else is truthy. Prefer explicit checks (if items:) over len when emptiness is the intent.

Q16 int vs float vs Decimal vs Fraction?

Answer int is arbitrary-precision. float is IEEE-754 binary floating point (rounding surprises). decimal.Decimal is for exact decimal arithmetic (money). fractions.Fraction is exact rational. Prefer Decimal/Fraction when binary float error matters.

Q17 What is hashing and which types are hashable?

Answer Hashable objects implement a stable __hash__ consistent with __eq__, so they can be dict keys or set elements. Immutables like str, int, frozenset, and tuples of hashables are hashable; lists/dicts/sets are not. User classes are hashable by identity unless you define __eq__ without __hash__.

Q18 What is duck typing?

Answer “If it walks like a duck…” — behaviour matters more than nominal type. APIs accept any object with the needed methods (e.g. file-like .read()). ABCs and Protocols document those interfaces formally.

Q19 bytes vs str vs bytearray?

Answer str is Unicode text. bytes is an immutable sequence of 0–255. bytearray is mutable bytes. Encode/decode at I/O boundaries (utf-8). Mixing str and bytes raises TypeError in most operations.

Strings & Text

Q20–Q28

Q20 Are Python strings mutable?

Answer No — str is immutable. Methods like replace/upper return new strings. That makes them safe as dict keys and shareable; for heavy building use list append + join or io.StringIO.

Q21 f-strings vs format vs %?

Answer f-strings (3.6+) are preferred for readability: f"{name}={value!r}". str.format and %-formatting still appear in older code. f-strings evaluate expressions at runtime; avoid untrusted input inside the braces (injection).

Q22 Important str methods to know?

Answer split/rsplit, join, strip/lstrip/rstrip, replace, find/index, startswith/endswith, isdigit/isalpha/isalnum, lower/upper/casefold, partition, encode, removeprefix/removesuffix (3.9+), and formatting with format specs.

Q23 What does str.join do and why prefer it?

Answer sep.join(iterable) concatenates string pieces with sep. It is the idiomatic, efficient way to build a string from parts — better than repeated + in a loop for many pieces.

Q24 raw strings and escape sequences?

Answer Raw strings (r"...") treat backslashes mostly literally — useful for regex and Windows paths. Normal strings interpret \n, \t, \\, etc. Note: a raw string cannot end with a single backslash.

Q25 How does Unicode work in Python 3?

Answer str holds Unicode code points. len(s) counts code points (not always user-perceived graphemes). Encode to bytes for files/sockets. Prefer UTF-8. casefold() is stronger than lower() for caseless matching.

Q26 String slicing rules?

Answer s[start:stop:step] — stop exclusive, negatives index from the end, out-of-range slices are clipped (no IndexError). s[::-1] reverses. Slicing a str returns a new str.

Q27 How do you interpolate and format numbers?

Answer f"{x:.2f}", f"{n:,}", f"{p:.1%}", format(x, "b") for binary, etc. Format mini-language controls width, alignment, precision, and type. Prefer f-strings in modern code.

Q28 What is the difference between split() and splitlines()?

Answer split() without args splits on any whitespace and drops empties; split("\n") uses that exact separator. splitlines() handles universal newlines and can keep ends with keepends=True.

Lists, Dicts, Sets & Collections

Q29–Q38

Q29 list vs tuple?

Answer list is mutable, variable-length sequence. tuple is immutable (and hashable if items are). Use tuples for fixed records, multiple return values, and dict keys; lists for growable homogeneous sequences.

Q30 How do list append, extend, and + differ?

Answer append(x) adds one element (even if x is a list, it becomes one nested item). extend(iterable) / += adds each element. + concatenates and returns a new list. Prefer append/extend for in-place building.

Q31 List comprehensions vs map/filter?

Answer Comprehensions [expr for x in it if cond] are usually clearer and fast enough. Generator expressions (parentheses) are lazy. map/filter with lambdas are fine but less Pythonic when a comprehension reads better.

Q32 dict key rules and insertion order?

Answer Keys must be hashable and unique; last write wins. Since Python 3.7, dict preserves insertion order as a language guarantee (3.6 CPython already did). views: keys(), values(), items().

Q33 dict.get vs [] vs setdefault vs | merge?

Answer d[k] raises KeyError if missing; get(k, default) returns default. setdefault(k, v) inserts v if missing and returns the value. 3.9+: d1 | d2 merges (right wins); |= updates in place.

Q34 set vs frozenset?

Answer set is mutable unordered unique elements; frozenset is immutable and hashable. Use sets for membership tests and math ops (| & - ^). Elements must be hashable.

Q35 What does collections offer that interviews expect?

Answer deque (O(1) ends), Counter, defaultdict, namedtuple / typing.NamedTuple, OrderedDict (mostly historical since dict is ordered), ChainMap, and abc collections. Know deque and Counter first.

Q36 How does sorting work?

Answer sorted(iterable, key=..., reverse=...) returns a new list; list.sort sorts in place. Timsort is stable. key should be cheap; use operator.itemgetter / attrgetter. For complex criteria, return a tuple key.

Q37 Shallow vs deep copy?

Answer Assignment binds another name to the same object. list.copy() / slicing / copy.copy are shallow — nested mutables are shared. copy.deepcopy recursively copies. Mutating a nested list after a shallow copy surprises beginners.

Q38 What is enumerate and zip?

Answer enumerate(iterable, start=0) yields (index, value). zip(a, b, ...) pairs until the shortest ends (3.10+: zip(..., strict=True) errors on unequal lengths). Unzip with zip(*pairs).

Functions & Scope

Q39–Q48

Q39 What is a first-class function?

Answer Functions are objects: assignable, passable as arguments, returnable, and storable in data structures. That enables higher-order functions, decorators, and callbacks.

Q40 LEGB scope rule?

Answer Name lookup order: Local, Enclosing (nonlocal), Global (module), Built-in. Assignment makes a name local unless declared global or nonlocal. Reading an outer name without assignment is fine.

Q41 global vs nonlocal?

Answer global binds a name to the module global. nonlocal binds to the nearest enclosing function scope (closures). Neither is needed for mutating a mutable object looked up via LEGB — only for rebinding the name.

Q42 Positional-only and keyword-only parameters?

Answer After / parameters are positional-only (3.8+). After * (or *args) parameters are keyword-only. Example: def f(a, b, /, *, c): .... Improves API clarity and allows renaming positional params safely.

Q43 What is a lambda?

Answer An anonymous expression-bodied function: lambda x: x + 1. Limited to one expression, no statements. Fine for short key= functions; prefer def for anything non-trivial (stack traces show names).

Q44 What are closures?

Answer An inner function that remembers enclosing variables via __closure__/cell. Classic pattern for factories and decorators. Watch late-binding in loops: capture with default args (lambda i=i: ...) when needed.

Q45 return vs yield vs yield from?

Answer return ends the function and provides a value (or None). yield pauses a generator and produces a value. yield from delegates to a subgenerator (and can return its StopIteration value).

Q46 What is functools.partial and lru_cache?

Answer partial freezes some arguments of a callable. lru_cache / cache memoises pure functions (hashable args). Use cache_clear when inputs’ meaning changes; avoid caching functions with side effects.

Q47 How do you annotate and document functions?

Answer Type hints on params/return, docstrings (Google/NumPy/Sphinx styles), and help()/__doc__. Prefer descriptive names over noisy comments. inspect.signature introspects parameters.

Q48 What is * unpacking in calls and assignments?

Answer f(*args, **kwargs) unpacks. Extended unpacking: a, *rest, b = seq. In 3.5+ you can also merge dicts with {**d1, **d2} and unpack iterables in lists [*a, *b].

OOP — Classes & Inheritance

Q49–Q60

Q49 What is a class and an instance in Python?

Answer A class is an object that creates instances via calling ClassName(...), which invokes __new__ then __init__. Instances hold per-object state in __dict__ (unless __slots__). Everything, including classes and functions, is an object.

Q50 __init__ vs __new__?

Answer __new__(cls, ...) is a static-like constructor that returns an instance (used for immutables/singletons). __init__(self, ...) initialises the instance and returns None. You rarely override __new__.

Q51 self and cls?

Answer Convention: instance methods take self; @classmethod methods take cls (the class); @staticmethod takes neither. Names are conventions — the binding behaviour comes from descriptors, not the identifier.

Q52 Instance vs class vs static methods?

Answer Instance: normal, receive self. classmethod: receive class, useful as alternate constructors (from_json). staticmethod: namespaced function with no automatic first arg — use sparingly when no class/instance state is needed.

Q53 What is inheritance and super()?

Answer class Sub(Base): inherits attributes. super() cooperates with MRO to call the next method — critical with multiple inheritance. Prefer super().__init__(...) over hard-coding Base.__init__.

Q54 What is the MRO?

Answer Method Resolution Order — the linearisation C3 algorithm uses for attribute lookup with multiple bases. See Class.__mro__ or help(Class). Diamond inheritance is handled so each class appears once in a consistent order.

Q55 What are dunder methods you must know?

Answer __repr__/__str__, __eq__/__hash__, __len__, __iter__/__next__, __getitem__, __enter__/__exit__, __call__, comparison methods, and numeric emulations. __repr__ should be unambiguous; __str__ user-friendly.

Q56 property, getters, and setters?

Answer @property turns a method into attribute-style access. Use .setter/.deleter for managed attributes. Prefer properties over getX/setX Java style when computation or validation is needed.

Q57 What are dataclasses (3.7+ / 3.10+)?

Answer @dataclass auto-generates __init__, __repr__, __eq__, etc. 3.10+ slots=True, kw_only, and match-friendly patterns. Great for data holders; still a normal class — add methods freely. Use field() for defaults/factories.

Q58 What are __slots__?

Answer A class attribute that lists fixed instance attribute names, skipping per-instance __dict__ (memory win, attribute typos fail fast). Inheritance needs care; weakrefs need explicit '__weakref__' if required.

Q59 Abstract base classes?

Answer abc.ABC and @abstractmethod force subclasses to implement methods. collections.abc (Sequence, Mapping, Iterable) document protocols. isinstance works with registered virtual subclasses.

Q60 Composition vs inheritance?

Answer Prefer composition (“has-a”) when reuse is about behaviour sharing without an is-a hierarchy. Inheritance couples types tightly. Mixins are multiple-inheritance style helpers that should stay thin.

Exception Handling

Q61–Q68

Q61 What is the exception hierarchy?

Answer BaseException → SystemExit, KeyboardInterrupt, GeneratorExit, and Exception. Catch Exception for most app errors; avoid bare except: and avoid catching BaseException unless you re-raise (you would swallow Ctrl+C).

Q62 try / except / else / finally?

Answer except handles matching types (tuple of types allowed). else runs if no exception in try. finally always runs for cleanup (unless the process is hard-killed). Prefer specific exceptions over broad ones.

Q63 raise and exception chaining?

Answer raise Exc(...) or raise to re-raise. raise New from original sets __cause__ (explicit chaining). Implicit chaining sets __context__ when raising inside an except. 3.11+ ExceptionGroup / except* for concurrent errors.

Q64 How do you create a custom exception?

Answer class AppError(Exception): ... — optionally store fields in __init__ and call super().__init__(message). Prefer a small hierarchy under one project base exception.

Q65 context managers and with?

Answer with expr as var: guarantees __exit__ for cleanup (files, locks). Implement via __enter__/__exit__ or contextlib.contextmanager. Prefer with open(...) over manual close.

Q66 What should you not do with exceptions?

Answer Do not use them for normal control flow when a simple check works. Do not except: pass and swallow bugs. Do not catch Exception just to log and continue without a strategy. Do not use exceptions for expected missing-key logic when .get is clearer — unless EAFP is the house style.

Q67 LBYL vs EAFP?

Answer Look Before You Leap: check then act (if key in d). Easier to Ask Forgiveness than Permission: try and handle (try: d[k] except KeyError). Python culture often prefers EAFP; both are valid when used consistently.

Q68 assert usage?

Answer assert condition, message is for internal invariants and can be stripped with python -O. Never use assert to validate untrusted external input in production — raise ValueError/TypeError explicitly.

Generators, Iterators & Decorators

Q69–Q77

Q69 Iterator vs iterable?

Answer Iterable: has __iter__ returning an iterator (or defines __getitem__ sequence protocol). Iterator: has __next__ and __iter__ returning self. for loops call iter() then next() until StopIteration.

Q70 What is a generator function?

Answer A function with yield — calling it returns a generator iterator. State is suspended between yields. Generators are lazy and memory-friendly for pipelines. return inside a generator raises StopIteration with a value (yield from captures it).

Q71 Generator expressions vs list comprehensions?

Answer (x*x for x in nums) is lazy; [x*x for x in nums] builds a full list. Use generators for large/infinite streams; materialise with list() only when needed.

Q72 What is a decorator?

Answer A callable that takes a function/class and returns a wrapped version. @dec above def is syntactic sugar for f = dec(f). Decorators implement logging, timing, retry, registration, and auth checks.

Q73 How do you write a decorator that takes arguments?

Answer Three nested layers: outer(args) returns mid(func) returns wrapper(*a, **k). Or use functools.partial patterns. Always functools.wraps(func) on the wrapper to preserve __name__/__doc__/signature helpers.

Q74 What does functools.wraps do?

Answer Copies metadata from the wrapped function onto the wrapper so debugging, help(), and some introspection still see the original. Without it, stack traces show wrapper.

Q75 classmethod/staticmethod/property as decorators?

Answer They are descriptor decorators built into the language. Order matters when stacking: @classmethod should typically be outermost relative to custom decorators that expect a raw function — know that descriptors change binding.

Q76 What is yield from used for?

Answer Delegating to another iterable/generator, forwarding send/throw, and retrieving the subgenerator’s return value. Cleaner than manual for x in sub: yield x for nested generators.

Q77 send(), throw(), and close() on generators?

Answer Advanced coroutine-style control: send injects a value as the result of yield; throw injects an exception; close raises GeneratorExit. Most app code only iterates; asyncio later formalised async coroutines separately.

Modules, Packages & Imports

Q78–Q84

Q78 module vs package?

Answer A module is a single .py file (or extension module). A package is a directory with __init__.py (namespace packages can omit it — PEP 420). import package.submodule loads the package hierarchy.

Q79 import mechanics and sys.modules?

Answer First import executes the module and caches it in sys.modules; later imports reuse the cache. from m import x binds x at import time — rebinding m.x later does not update an already-imported name x.

Q80 absolute vs relative imports?

Answer Absolute: import pkg.mod / from pkg.mod import f. Relative: from . import sibling / from ..parent import x — only inside packages. Prefer absolute imports in application code for clarity.

Q81 What is if __name__ == "__main__":?

Answer True when the file is run as the entry script, false when imported. Put CLI/demo code under that guard so importing the module does not run side effects.

Q82 VIRTUAL ENV and dependency management?

Answer venv/virtualenv isolate site-packages. pip installs distributions; requirements.txt or lock files (pip-tools, poetry, uv, pdm) pin versions. Never install project deps into the system Python casually.

Q83 __init__.py roles?

Answer Marks a regular package, can run package-level setup, and re-export a public API. Keep it light. Namespace packages (no __init__.py) allow split packages across paths.

Q84 What is PYTHONPATH and how do imports find modules?

Answer sys.path is searched (script dir, PYTHONPATH, stdlib, site-packages). Editable installs and src layouts affect this. Prefer installing your package over hacking sys.path in production code.

Concurrency & Parallelism

Q85–Q92

Q85 What is the GIL?

Answer CPython’s Global Interpreter Lock allows only one thread to execute Python bytecode at a time. Threads help I/O concurrency, not CPU-bound parallelism. CPU-bound work uses multiprocessing, native extensions that release the GIL, or newer free-threaded builds (experimental/optional in recent CPythons).

Q86 threading vs multiprocessing vs asyncio?

Answer threading: shared memory, good for I/O, GIL-bound for pure Python CPU. multiprocessing: separate processes, true parallelism, higher overhead/IPC. asyncio: single-threaded cooperative concurrency for many sockets via event loop and async/await.

Q87 How do you start a thread?

Answer threading.Thread(target=fn, args=...).start(); join() to wait. Prefer concurrent.futures.ThreadPoolExecutor for pools. Do not call run() if you want a new thread — start() does that.

Q88 Locks, RLock, Event, Queue?

Answer Lock/RLock serialise critical sections; Event signals; Condition for wait/notify; queue.Queue is thread-safe for producer-consumer. Prefer Queue over sharing raw lists across threads.

Q89 What is concurrent.futures?

Answer ThreadPoolExecutor and ProcessPoolExecutor with a unified Future API (submit, map, as_completed, result, cancel). High-level replacement for manual thread/process management.

Q90 async def / await basics?

Answer async def defines a coroutine function; await suspends until an awaitable completes. Run with asyncio.run(main()). Use asyncio.gather / TaskGroup (3.11+) for concurrency. Do not call blocking I/O inside async without an executor.

Q91 Race conditions in Python?

Answer Even with the GIL, compound operations (read-modify-write on shared data structures, check-then-act) can race. Protect shared mutable state with locks or avoid sharing (queue ownership, process isolation).

Q92 When is multiprocessing the right choice?

Answer CPU-heavy pure-Python workloads, sandboxing, or bypassing the GIL. Pickle-able callables/args, careful about Windows spawn, and avoid huge shared dicts without managers/shared memory.

Coding & Output Puzzles

Q93–Q100

Q93 What does this print? a = [1, 2, 3]; b = a; b.append(4); print(a)

Answer [1, 2, 3, 4] — b and a reference the same list; append mutates in place.

Q94 What does this print? print(bool([]), bool([0]), bool(""))

Answer False True False — empty list and empty string are falsy; a non-empty list is truthy even if it contains 0.

Q95 What does this print? x = (i for i in range(3)); print(list(x)); print(list(x))

Answer [0, 1, 2] then [] — a generator is exhausted after one full iteration.

Q96 What does this print? print("ab" * 3); print([1, 2] * 2)

Answer ababab and [1, 2, 1, 2] — * repeats sequences; for lists this aliases references when repeating mutable elements (careful with [[0]]*3).

Q97 What does this print? def f(x=[]): x.append(1); return x; print(f()); print(f())

Answer [1] then [1, 1] — the default list is created once and reused across calls. (Note: print(f(), f()) would show [1, 1] [1, 1] because both calls share the same list before printing.)

Q98 What does this print? a = [1, 2, 3]; print(a[::-1]); print(a)

Answer [3, 2, 1] then [1, 2, 3] — slicing reverses into a new list; a is unchanged.

Q99 What does this print? d = {True: "yes", 1: "no", 1.0: "maybe"}; print(d)

Answer {True: 'maybe'} — True == 1 == 1.0 and they collide as the same dict key (hash/eq); last write wins, key display stays the first-inserted True.

Q100 What does this print? print(0.1 + 0.2 == 0.3)

Answer False — binary float rounding; 0.1 + 0.2 is slightly above 0.3. Use math.isclose or Decimal for exactness needs.