Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Interview questions with answers

Python interview questions and answers

Data model, generators, decorators, async, typing and the GIL. Open any question to read its model answer; the multiple-choice set marks the right option and explains it.

Subjective
30
Objective
30

Subjective questions 30

1Lists vs. tuples vs. sets vs. dictionaries: when do you use each?Asked almost every time

Lists are ordered, mutable sequences for collections you change. Tuples are ordered and immutable, for fixed records and dictionary keys. Sets hold unique, hashable items with fast membership tests and set algebra. Dictionaries map keys to values with average O(1) lookup and keep insertion order (Python 3.7+).

2What are decorators and how do they work?Asked almost every time

A decorator is a callable that takes a function and returns a new one, applied with @name above the definition. It wraps behaviour such as logging, caching, retries or access checks around the original. Use functools.wraps so the wrapper keeps the original name and docstring. Decorators with arguments are factories that return the decorator.

3Explain generators and yield.Asked almost every time

A function with yield returns a generator, an iterator that produces values lazily, pausing at each yield and resuming on the next next(). It uses constant memory for long or infinite sequences, such as reading a large file line by line. Generator expressions (x*x for x in data) are the lazy form of list comprehensions.

4What is the GIL and how does it affect concurrency?Asked almost every time

CPython's Global Interpreter Lock lets only one thread run Python bytecode at a time, so threads do not speed up CPU-bound work but are fine for I/O-bound work, because the lock is released while waiting. Use multiprocessing or native extensions for CPU-bound work, and asyncio for many concurrent I/O tasks. Python 3.13+ also offers an experimental free-threaded build without the GIL.

5What are list, dict and set comprehensions, and when should you avoid them?Asked almost every time

Compact expressions that build collections: [x*x for x in nums if x > 0], {k: v for k, v in pairs}, {w.lower() for w in words}. They are faster and clearer than loops for simple transforms, but avoid nesting them deeply or using them for side effects; use a regular loop for readability.

6How does exception handling work in Python?Asked almost every time

try runs code; except SomeError as e handles specific errors; else runs if nothing failed; finally always runs for cleanup. Catch specific exceptions, re-raise with raise or chain with raise NewError() from e, and define custom exceptions by subclassing Exception.

7What are iterators and the iterator protocol?Asked almost every time

An iterable has __iter__ returning an iterator; an iterator has __next__ that returns the next item or raises StopIteration. for loops, comprehensions and many built-ins use this protocol, and generators implement it automatically.

8Threads vs. processes vs. asyncio: when do you use each?Asked almost every time

Use asyncio for many concurrent I/O tasks with async libraries; threads for I/O with blocking libraries; processes (multiprocessing, ProcessPoolExecutor) for CPU-bound work, since the GIL lets only one thread run Python bytecode at a time. Free-threaded builds in 3.13+ are changing this.

9How does asyncio work?Very often asked

An event loop runs coroutines defined with async def. await pauses a coroutine until an awaitable (a network call, asyncio.sleep) completes, letting other coroutines run meanwhile. asyncio.gather or TaskGroup runs tasks concurrently. It is single-threaded cooperative multitasking, ideal for many network connections; blocking calls must be avoided or run in a thread.

10Mutable default arguments: what is the bug?Very often asked

Default values are evaluated once, when the function is defined. def add(item, items=[]) shares one list across calls, so items accumulate. Use items=None and create a new list inside the function.

11Shallow copy vs. deep copy?Very often asked

A shallow copy (list(x), x.copy(), copy.copy) creates a new outer container that still references the same inner objects. A deep copy (copy.deepcopy) recursively copies everything, so nested changes do not affect the original.

12What are context managers?Very often asked

Objects used with with that set something up and guarantee clean-up, even on errors, through __enter__ and __exit__: files, locks, database transactions. contextlib.contextmanager lets you write one as a generator with a single yield.

13How do type hints help, and are they enforced?Very often asked

Hints such as def total(prices: list[float]) -> float document intent, power editor completion and let static checkers (mypy, Pyright) catch bugs before running. Python does not enforce them at runtime; libraries such as Pydantic can validate data against them.

14What are @staticmethod, @classmethod and instance methods?Very often asked

Instance methods take self and work with one object. Class methods take cls and are often alternative constructors (from_json). Static methods take neither; they are plain functions grouped in the class namespace.

15What is a property and why use it?Very often asked

@property turns a method into an attribute-like getter, with optional setter and deleter. It lets you add validation or computed values later without changing how callers access the attribute.

16How does inheritance and MRO work?Very often asked

Classes can inherit from several bases; Python resolves attributes with the method resolution order (C3 linearisation), visible in Class.__mro__. super() calls the next class in the MRO, which makes cooperative multiple inheritance work.

17What are closures and the nonlocal keyword?Very often asked

A closure is an inner function that remembers variables from its enclosing scope even after it returns. To reassign such a variable inside the inner function, declare it nonlocal; otherwise Python treats it as a new local.

18What is __slots__?Very often asked

Declaring __slots__ = ('x', 'y') on a class removes the per-instance __dict__, saving memory and making attribute access slightly faster, at the cost of not being able to add new attributes dynamically.

19How do you write tests in Python?Very often asked

Use pytest: plain functions with assert, fixtures for setup, parametrize for many cases, monkeypatch or unittest.mock for dependencies, and coverage reports. Keep tests fast and independent.

20What are *args and **kwargs?Often asked

*args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dictionary. They let functions accept flexible arguments and forward them, which is common in decorators and wrappers.

21Explain __init__, __repr__ and other dunder methods.Often asked

Dunder (double underscore) methods hook into Python's data model: __init__ initialises a new object, __repr__ gives an unambiguous representation, __str__ a readable one, __eq__ and __hash__ define equality and hashing, __len__, __iter__ and __getitem__ make objects behave like containers. Dataclasses generate many of them for you.

22How does Python manage memory?Often asked

Mainly by reference counting: an object is freed when no references remain. A cyclic garbage collector finds groups of objects that reference each other but are unreachable. Small objects come from private memory pools.

23How do you manage dependencies and environments?Often asked

Create an isolated virtual environment per project (python -m venv or tools like uv and Poetry), declare dependencies in pyproject.toml, and lock exact versions for reproducible installs. Never install project packages into the system Python.

24What are dataclasses vs. Pydantic models?Often asked

Dataclasses generate __init__, __repr__ and comparisons for plain data containers without validation. Pydantic models validate and convert input at runtime, serialise to JSON and generate schemas, which suits API boundaries and configuration.

25What is the walrus operator?Often asked

:= assigns and returns a value inside an expression, for example while (line := f.readline()): or if (n := len(items)) > 10:. Use it to avoid repeating a computation, but not at the cost of clarity.

26What are match statements?Often asked

Structural pattern matching (3.10+): match command: with case patterns that can destructure sequences, mappings and class instances, bind variables and add guards. It is more powerful than a simple switch.

27How do you profile and speed up Python code?Often asked

Measure first with cProfile, timeit or py-spy. Then use better algorithms and data structures, built-ins and comprehensions, vectorised NumPy, caching (functools.cache), concurrency for I/O, or move hot loops to compiled code.

28What is the difference between __str__ and __repr__?Often asked

__repr__ is an unambiguous developer representation, ideally valid code to recreate the object; __str__ is a readable user-facing string. print uses __str__, falling back to __repr__.

29What is the difference between is and ==?Sometimes asked

== compares values using __eq__; is checks whether two names point to the same object. Use is only for singletons such as None.

30What are virtual environments and why use them?Sometimes asked

Isolated Python installations per project (python -m venv .venv, or tools like uv and Poetry) so each project has its own dependency versions without conflicts or touching the system Python.

Objective questions 30

1Which type is immutable?Asked almost every time
  1. Aset
  2. Blist
  3. Cdict
  4. DtupleCorrect answer

Why: Tuples cannot be changed after creation.

2What does yield turn a function into?Asked almost every time
  1. AA class
  2. BA generatorCorrect answer
  3. CA coroutine only
  4. DA lambda

Why: Calling it returns a lazy generator.

3The GIL mostly limits…Asked almost every time
  1. AMultiprocessing
  2. Basyncio
  3. CI/O-bound threads
  4. DCPU-bound threads running Python codeCorrect answer

Why: Only one thread executes bytecode at a time.

4Which block always runs, error or not?Asked almost every time
  1. Aelse
  2. Bexcept
  3. Cwith
  4. DfinallyCorrect answer

Why: Used for cleanup.

5Which is best for CPU-bound work in standard CPython?Asked almost every time
  1. AA bigger loop
  2. BProcessesCorrect answer
  3. CThreads
  4. Dasyncio

Why: The GIL limits threads for Python code.

6What does __next__ raise when an iterator is exhausted?Asked almost every time
  1. AKeyError
  2. BNone
  3. CStopIterationCorrect answer
  4. DIndexError

Why: for loops catch it.

7What is printed?Very often asked
def add(x, items=[]):
    items.append(x)
    return items

print(add(1))
print(add(2))
  1. A[1] then [2]
  2. B[1] then [1, 2]Correct answer
  3. CError
  4. D[] then []

Why: The default list is shared between calls.

8Which keyword defines a coroutine?Very often asked
  1. Aasync defCorrect answer
  2. Bcoroutine def
  3. Cawait def
  4. Ddef async

Why: async def functions return coroutines.

9What does functools.wraps preserve?Very often asked
  1. AType hints only at runtime
  2. BSpeed
  3. CThe wrapped function's name and docstringCorrect answer
  4. DGlobal variables

Why: It copies metadata onto the wrapper.

10Which creates a deep copy?Very often asked
  1. Alist(x)
  2. Bx[:]
  3. Ccopy.deepcopy(x)Correct answer
  4. Dx.copy()

Why: Only deepcopy copies nested objects too.

11Which decorator creates an alternative constructor?Very often asked
  1. A@dataclass
  2. B@classmethodCorrect answer
  3. C@staticmethod
  4. D@property

Why: It receives cls.

12Which keyword reassigns a variable from an enclosing function?Very often asked
  1. Aglobal
  2. Bouter
  3. Cstatic
  4. DnonlocalCorrect answer

Why: Otherwise a new local is made.

13What does __slots__ mainly save?Very often asked
  1. ADisk space
  2. BImport time
  3. CCPU in loops only
  4. DMemory per instanceCorrect answer

Why: No per-instance __dict__.

14Which validates data at runtime?Very often asked
  1. AType hints alone
  2. BDataclasses
  3. CComments
  4. DPydantic modelsCorrect answer

Why: Pydantic converts and validates input.

15Which shows a class's method resolution order?Very often asked
  1. AClass.__bases__ only
  2. Bdir(Class)
  3. CClass.order()
  4. DClass.__mro__Correct answer

Why: C3 linearisation.

16What does [x * 2 for x in range(3)] give?Often asked
  1. A[2, 4, 6]
  2. B(0, 2, 4)
  3. C[0, 1, 2]
  4. D[0, 2, 4]Correct answer

Why: range(3) is 0, 1, 2.

17Which method makes an object usable in a with block?Often asked
  1. A__call__
  2. B__enter__ and __exit__Correct answer
  3. C__iter__
  4. D__new__

Why: Context managers implement both.

18**kwargs collects extra arguments into a…Often asked
  1. Alist
  2. Btuple
  3. CdictCorrect answer
  4. Dset

Why: Keyword arguments become a dictionary.

19Which is the right way to test for None?Often asked
  1. ANone in x
  2. Bx == None
  3. Cx is NoneCorrect answer
  4. Dx.equals(None)

Why: None is a singleton; use identity.

20Average lookup time in a dict is…Often asked
  1. AO(1)Correct answer
  2. BO(log n)
  3. CO(n²)
  4. DO(n)

Why: Hash tables give constant average lookup.

21What does := do?Often asked
  1. ACompares types
  2. BDeclares a constant
  3. CDeletes a name
  4. DAssigns inside an expressionCorrect answer

Why: The walrus operator.

22Which tool profiles function calls?Often asked
  1. AcProfileCorrect answer
  2. Bpip
  3. Cvenv
  4. Dblack

Why: Built into the standard library.

23Which pytest feature runs a test with many inputs?Often asked
  1. Afixture scope
  2. Bmonkeypatch
  3. Cskip
  4. DparametrizeCorrect answer

Why: @pytest.mark.parametrize.

24What does print(obj) call first?Often asked
  1. A__str__Correct answer
  2. B__repr__
  3. C__format__ only
  4. D__call__

Why: Falls back to __repr__.

25What does raise NewError() from e do?Often asked
  1. AChains the original exceptionCorrect answer
  2. BHides it
  3. CRetries
  4. DLogs only

Why: The traceback shows both.

26Which caches function results by arguments?Often asked
  1. Acontextlib.suppress
  2. Bfunctools.cacheCorrect answer
  3. Cfunctools.partial
  4. Ditertools.cycle

Why: Memoisation.

27Which runs several coroutines concurrently?Sometimes asked
  1. Aasyncio.gather()Correct answer
  2. Btime.sleep()
  3. Cthreading.join()
  4. Dmap()

Why: gather schedules them together and collects results.

28What does @dataclass generate?Sometimes asked
  1. AA database table
  2. B__init__, __repr__ and __eq__Correct answer
  3. CAsync methods
  4. DA REST API

Why: Dataclasses write boilerplate methods from field annotations.

29Which version introduced match statements?Sometimes asked
  1. A3.6
  2. B2.7
  3. C3.0
  4. D3.10Correct answer

Why: Structural pattern matching.

30Which command creates a virtual environment?Sometimes asked
  1. Apython -m venv .venvCorrect answer
  2. Bpip env
  3. Cpython --isolate
  4. Dvenv install

Why: Isolates dependencies.

Track what you have practised and search every bank in your dashboard.

Start learning