Python Interview Questions & Answers
Python Interview Questions &
Answers
200 Comprehensive Questions for Technical Interviews
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Contents:
Part 1: Easy Questions (1-100) — Fundamentals, Syntax & Basics
Part 2: Hard Questions (1-100) — Advanced Concepts, Internals & Patterns
Page 1 of 28
Python Interview Questions & Answers
PART 1: EASY QUESTIONS
Fundamentals, Syntax, Data Types & Basic Concepts
Q1: What is Python?
Answer: Python is a high-level, interpreted, general-purpose programming language. It
emphasizes code readability with significant indentation and supports multiple
programming paradigms including procedural, object-oriented, and functional
programming.
Q2: What are the key features of Python?
Answer: Key features include: easy to learn and read syntax, interpreted language (no
compilation needed), dynamically typed, extensive standard library, cross-platform
compatibility, supports multiple paradigms, automatic memory management, and large
community support.
Q3: What is PEP 8?
Answer: PEP 8 is Python's official style guide for writing clean, readable code. It covers
naming conventions, indentation (4 spaces), line length (79 characters max), imports
organization, whitespace usage, and comments formatting.
Q4: What are Python's built-in data types?
Answer: Built-in data types include: Numeric (int, float, complex), Sequence (str, list,
tuple), Set (set, frozenset), Mapping (dict), Boolean (bool), Binary (bytes, bytearray,
memoryview), and None type.
Q5: What is the difference between a list and a tuple?
Answer: Lists are mutable (can be modified), use square brackets [], and are slower.
Tuples are immutable (cannot be modified), use parentheses (), are faster, and can be
used as dictionary keys. Use tuples for fixed data, lists for dynamic data.
Q6: How do you create a list in Python?
Answer: Lists can be created using: square brackets my_list = [1, 2, 3], list() constructor
list([1, 2, 3]), or list comprehension [x for x in range(5)]. Lists can contain mixed data
types.
Q7: What is a dictionary in Python?
Answer: A dictionary is an unordered collection of key-value pairs. Keys must be unique
and immutable (strings, numbers, tuples). Created with curly braces: my_dict = {'name':
'John', 'age': 30}. Access values using keys: my_dict['name'].
Q8: What is the difference between == and is?
Answer: == compares values (equality), checking if two objects have the same value. 'is'
compares identity, checking if two references point to the same object in memory.
Example: a = [1,2]; b = [1,2]; a == b is True, but a is b is False.
Q9: What are Python comments?
Answer: Single-line comments start with #. Multi-line comments use triple quotes (''' or
"""). Docstrings (documentation strings) use triple quotes at the start of
functions/classes/modules to document them.
Page 2 of 28
Python Interview Questions & Answers
Q10: What is indentation in Python?
Answer: Indentation defines code blocks in Python (instead of braces). Standard is 4
spaces per level. It's mandatory and enforced by the interpreter. Inconsistent indentation
causes IndentationError.
Page 3 of 28
Python Interview Questions & Answers
Q11: What is a variable in Python?
Answer: A variable is a name that references a value in memory. Python variables are
dynamically typed (type determined at runtime). Created by assignment: x = 10. No
declaration needed. Names are case-sensitive and follow naming conventions.
Q12: How do you take user input in Python?
Answer: Use the input() function: name = input('Enter name: '). It always returns a string.
Convert to other types as needed: age = int(input('Enter age: ')). In Python 2, use
raw_input() instead.
Q13: What is the print() function?
Answer: print() outputs data to console. Syntax: print(*objects, sep=' ', end='\n').
Examples: print('Hello'), print(a, b, c), print('Hi', end=''), print(1, 2, sep='-'). Supports f-
strings: print(f'Name: {name}').
Q14: What are f-strings in Python?
Answer: F-strings (formatted string literals) allow embedding expressions inside strings
using f prefix. Syntax: f'Hello {name}'. Supports expressions: f'Sum: {2+3}', formatting:
f'{price:.2f}', and method calls: f'{[Link]()}'.
Q15: What is type() function?
Answer: type() returns the type of an object. Example: type(5) returns <class 'int'>,
type('hello') returns <class 'str'>. Useful for debugging and type checking. Can also
create new types dynamically.
Q16: What is len() function?
Answer: len() returns the number of items in a container. Works with strings (character
count), lists, tuples, dictionaries (key count), sets. Example: len('hello') returns 5,
len([1,2,3]) returns 3.
Q17: What are arithmetic operators in Python?
Answer: Arithmetic operators: + (addition), - (subtraction), * (multiplication), / (division,
returns float), // (floor division), % (modulus), ** (exponentiation). Example: 7//2 = 3, 7%2
= 1, 2**3 = 8.
Q18: What are comparison operators?
Answer: Comparison operators: == (equal), != (not equal), > (greater than), < (less
than), >= (greater or equal), <= (less or equal). Return Boolean values. Can be chained:
1 < x < 10.
Q19: What are logical operators?
Answer: Logical operators: and (both true), or (at least one true), not (negation). Used
for combining conditions. Short-circuit evaluation: 'and' stops at first False, 'or' stops at
first True.
Q20: What is an if statement?
Answer: if statement executes code conditionally. Syntax: if condition: code. Use elif for
additional conditions, else for default. Example: if x > 0: print('positive') elif x < 0:
print('negative') else: print('zero').
Page 4 of 28
Python Interview Questions & Answers
Q21: What is a for loop?
Answer: for loop iterates over sequences. Syntax: for item in iterable: code. Works with
lists, strings, ranges, dictionaries. Example: for i in range(5): print(i). Use enumerate() for
index and value.
Q22: What is a while loop?
Answer: while loop executes while condition is true. Syntax: while condition: code.
Example: while x > 0: x -= 1. Be careful of infinite loops. Use break to exit, continue to
skip iteration.
Q23: What is the range() function?
Answer: range() generates a sequence of numbers. Syntax: range(stop), range(start,
stop), range(start, stop, step). Returns range object (memory efficient). Example:
range(5) gives 0,1,2,3,4. range(1,10,2) gives 1,3,5,7,9.
Q24: What are break and continue statements?
Answer: break exits the loop entirely. continue skips to next iteration. Example: for i in
range(10): if i == 5: break (stops at 5). for i in range(10): if i == 5: continue (skips 5,
continues to 6).
Q25: What is a function in Python?
Answer: A function is a reusable block of code defined with def keyword. Syntax: def
function_name(parameters): code return value. Functions promote code reuse,
modularity, and readability. Can have default parameters and return multiple values.
Q26: What is the return statement?
Answer: return exits a function and optionally returns a value. Functions without return
(or with return alone) return None. Can return multiple values as tuple: return x, y, z.
Once return executes, function exits immediately.
Q27: What are default parameters?
Answer: Default parameters have preset values if no argument provided. Syntax: def
greet(name='World'): print(f'Hello {name}'). Call: greet() prints 'Hello World', greet('Alice')
prints 'Hello Alice'. Default params must come after non-default.
Q28: What are *args and **kwargs?
Answer: *args collects positional arguments into a tuple. **kwargs collects keyword
arguments into a dictionary. Example: def func(*args, **kwargs): allows func(1, 2, a=3,
b=4). Used for flexible function signatures.
Q29: What is a lambda function?
Answer: Lambda is an anonymous, single-expression function. Syntax: lambda
arguments: expression. Example: square = lambda x: x**2. Commonly used with map(),
filter(), sorted(). Limited to one expression, no statements.
Q30: What is the map() function?
Answer: map() applies a function to each item in an iterable. Syntax: map(function,
iterable). Returns map object (lazy evaluation). Example: list(map(lambda x: x*2, [1,2,3]))
returns [2,4,6]. Can use with multiple iterables.
Page 5 of 28
Python Interview Questions & Answers
Q31: What is the filter() function?
Answer: filter() returns items where function returns True. Syntax: filter(function,
iterable). Example: list(filter(lambda x: x > 0, [-1, 0, 1, 2])) returns [1, 2]. Function must
return boolean.
Q32: What is list comprehension?
Answer: List comprehension creates lists concisely. Syntax: [expression for item in
iterable if condition]. Example: [x**2 for x in range(5)] gives [0,1,4,9,16]. [x for x in
range(10) if x%2==0] gives even numbers.
Q33: What is dictionary comprehension?
Answer: Dictionary comprehension creates dictionaries concisely. Syntax: {key: value
for item in iterable}. Example: {x: x**2 for x in range(5)} gives {0:0, 1:1, 2:4, 3:9, 4:16}.
Can include conditions.
Q34: What is a module in Python?
Answer: A module is a Python file containing definitions and statements. Import with:
import module_name, from module import function, or from module import *. Modules
promote code organization and reuse. Create by saving code as .py file.
Q35: What is a package in Python?
Answer: A package is a directory containing modules and an __init__.py file. Allows
hierarchical organization. Import: import [Link] or from package import
module. __init__.py can be empty or contain initialization code.
Q36: How do you import modules?
Answer: Import methods: import math (use [Link]()), from math import sqrt (use
sqrt() directly), from math import * (import all), import numpy as np (alias). Imports
searched in [Link].
Q37: What is pip?
Answer: pip is Python's package installer. Commands: pip install package, pip uninstall
package, pip list (installed packages), pip freeze > [Link], pip install -r
[Link]. Installs from PyPI repository.
Q38: What is __name__ == '__main__'?
Answer: This condition checks if script is run directly (not imported). Code inside only
executes when file is run as main program. Useful for having test code that doesn't run
on import. __name__ is '__main__' when run directly, module name when imported.
Q39: What is exception handling?
Answer: Exception handling manages runtime errors gracefully. Use try-except blocks:
try: risky_code except ExceptionType: handle_error. Prevents crashes, allows recovery.
Add finally for cleanup code that always runs.
Q40: What are common exceptions in Python?
Answer: Common exceptions: ValueError (wrong value type), TypeError (wrong
operation for type), IndexError (index out of range), KeyError (dictionary key not found),
FileNotFoundError, ZeroDivisionError, AttributeError, ImportError, NameError.
Page 6 of 28
Python Interview Questions & Answers
Q41: What is the finally block?
Answer: finally block executes regardless of whether exception occurred. Used for
cleanup (closing files, releasing resources). Syntax: try: code except: handler finally:
cleanup. Finally runs even if return in try/except.
Q42: How do you raise an exception?
Answer: Use raise statement: raise ValueError('Invalid input'). Can raise built-in or
custom exceptions. Re-raise current exception with just 'raise'. Use for input validation,
error signaling.
Q43: What is a class in Python?
Answer: A class is a blueprint for creating objects. Defined with class keyword. Contains
attributes (data) and methods (functions). Example: class Dog: def __init__(self, name):
[Link] = name. Creates objects: my_dog = Dog('Buddy').
Q44: What is __init__ method?
Answer: __init__ is the constructor method called when creating objects. Initializes
instance attributes. First parameter is self (reference to instance). Example: def
__init__(self, name): [Link] = name. Not required but commonly used.
Q45: What is self in Python?
Answer: self is a reference to the current instance of the class. Used to access
attributes and methods within the class. Must be first parameter in instance methods.
Name 'self' is convention, not keyword.
Q46: What is inheritance?
Answer: Inheritance allows a class to inherit attributes and methods from another class.
Syntax: class Child(Parent). Child class can override parent methods. Use super() to call
parent methods. Promotes code reuse.
Q47: What is method overriding?
Answer: Method overriding is redefining a parent class method in child class. Same
method name, different implementation. Called based on object type (polymorphism).
Use super().method() to call parent version.
Q48: What is encapsulation?
Answer: Encapsulation bundles data and methods that work on data within a class.
Controls access using naming conventions: _protected (single underscore), __private
(double underscore). Python doesn't enforce strict access control.
Q49: What are class attributes vs instance attributes?
Answer: Class attributes are shared by all instances (defined outside __init__). Instance
attributes are unique to each instance (defined with self in __init__). Access:
[Link] or [Link]. Class attrs save memory for shared data.
Q50: What is a string in Python?
Answer: String is an immutable sequence of characters. Created with single, double, or
triple quotes. Supports indexing [0], slicing [1:4], concatenation (+), repetition (*). Many
built-in methods: upper(), lower(), split(), join().
Page 7 of 28
Python Interview Questions & Answers
Q51: What are common string methods?
Answer: Common methods: upper(), lower(), strip(), split(), join(), replace(), find(),
count(), startswith(), endswith(), isalpha(), isdigit(), format(). Strings are immutable,
methods return new strings.
Q52: What is string slicing?
Answer: Slicing extracts substring using [start:stop:step]. Examples: s[0:5] (chars 0-4),
s[:5] (first 5), s[5:] (from index 5), s[-1] (last char), s[::-1] (reverse). Stop index is
exclusive.
Q53: What is the split() method?
Answer: split() divides string into list by delimiter. Default delimiter is whitespace.
Example: 'a,b,c'.split(',') returns ['a','b','c']. 'hello world'.split() returns ['hello', 'world'].
Optional maxsplit parameter.
Q54: What is the join() method?
Answer: join() combines list elements into string with separator. Syntax:
[Link](list). Example: ','.join(['a','b','c']) returns 'a,b,c'. ' '.join(['Hello', 'World'])
returns 'Hello World'. Elements must be strings.
Q55: How do you convert data types?
Answer: Type conversion functions: int(), float(), str(), list(), tuple(), set(), dict(), bool().
Example: int('42') = 42, str(42) = '42', list('abc') = ['a','b','c']. Invalid conversions raise
ValueError.
Q56: What is None in Python?
Answer: None is Python's null value, representing absence of value. It's a singleton
(only one None object). Used for default parameters, uninitialized variables, function
returns without explicit return. Check with 'is None'.
Q57: What is Boolean in Python?
Answer: Boolean represents True or False values. Used in conditions and logical
operations. Falsy values: False, None, 0, '', [], {}, set(). Everything else is truthy. bool()
converts to Boolean.
Q58: What is the pass statement?
Answer: pass is a null operation placeholder. Does nothing but prevents syntax errors in
empty blocks. Used in: empty functions, classes, loops, conditionals during development.
Example: def placeholder(): pass.
Q59: What is the assert statement?
Answer: assert tests conditions during debugging. Syntax: assert condition, 'error
message'. Raises AssertionError if condition is False. Disabled with -O flag
(optimization). Use for internal checks, not validation.
Q60: How do you open a file in Python?
Answer: Use open() function: file = open('filename', 'mode'). Modes: 'r' (read), 'w' (write),
'a' (append), 'b' (binary), '+' (read/write). Better: use with statement for automatic closing:
with open('file') as f: data = [Link]().
Page 8 of 28
Python Interview Questions & Answers
Q61: What is the with statement?
Answer: with statement manages resources with context managers. Ensures cleanup
(like closing files) even if errors occur. Syntax: with open('file') as f: content = [Link]().
Preferred over try-finally for resource management.
Q62: How do you read a file?
Answer: Reading methods: read() (entire file), readline() (one line), readlines() (list of
lines). Example: with open('[Link]') as f: content = [Link](). For large files, iterate: for line
in f: process(line).
Q63: How do you write to a file?
Answer: Writing: open with 'w' (overwrite) or 'a' (append) mode. Use write() or
writelines(). Example: with open('[Link]', 'w') as f: [Link]('Hello'). 'w' creates file if not
exists, overwrites if exists.
Q64: What is the append() method for lists?
Answer: append() adds single element to end of list. Syntax: [Link](element).
Modifies list in-place, returns None. Example: nums = [1,2]; [Link](3) gives
[1,2,3]. For multiple elements, use extend().
Q65: What is the extend() method?
Answer: extend() adds all elements from iterable to list. Syntax: [Link](iterable).
Example: a = [1,2]; [Link]([3,4]) gives [1,2,3,4]. Different from append: append([3,4])
gives [1,2,[3,4]].
Q66: What is the pop() method?
Answer: pop() removes and returns element at index (default last). Syntax:
[Link](index). Example: nums = [1,2,3]; [Link]() returns 3, list becomes [1,2].
[Link](0) returns 1. Raises IndexError if empty.
Q67: What is the remove() method?
Answer: remove() removes first occurrence of value. Syntax: [Link](value). Raises
ValueError if not found. Example: nums = [1,2,3,2]; [Link](2) gives [1,3,2]. Only
removes first match.
Q68: What is the sort() method?
Answer: sort() sorts list in-place. Syntax: [Link](key=None, reverse=False). Example:
[Link]() ascending, [Link](reverse=True) descending. Modifies original list,
returns None. For new sorted list, use sorted().
Q69: What is the sorted() function?
Answer: sorted() returns new sorted list from iterable. Original unchanged. Syntax:
sorted(iterable, key=None, reverse=False). Works on any iterable. Example:
sorted([3,1,2]) returns [1,2,3]. sorted('cba') returns ['a','b','c'].
Q70: What is the reverse() method?
Answer: reverse() reverses list in-place. Returns None. Example: nums = [1,2,3];
[Link]() gives [3,2,1]. For reversed copy, use: list(reversed(nums)) or nums[::-1].
Page 9 of 28
Python Interview Questions & Answers
Q71: What is the index() method?
Answer: index() returns first index of value. Syntax: [Link](value, start, end). Raises
ValueError if not found. Example: [1,2,3,2].index(2) returns 1. Also works with strings.
Q72: What is the count() method?
Answer: count() returns number of occurrences of value. Works with lists and strings.
Example: [1,2,2,3].count(2) returns 2. 'hello'.count('l') returns 2. Returns 0 if not found.
Q73: What is the copy() method?
Answer: copy() creates shallow copy of list/dictionary. Changes to copy don't affect
original (for simple values). Example: b = [Link](). For nested structures, use
[Link]() from copy module.
Q74: What are set operations in Python?
Answer: Sets support: union (|), intersection (&), difference (-), symmetric difference (^).
Methods: union(), intersection(), difference(), symmetric_difference(), issubset(),
issuperset(). Sets are unordered, contain unique elements.
Q75: How do you add/remove set elements?
Answer: Add: [Link](element), [Link](iterable). Remove: [Link](element)
raises error if missing, [Link](element) doesn't. [Link]() removes arbitrary element.
[Link]() empties set.
Q76: What is the get() method for dictionaries?
Answer: get() returns value for key, or default if key not found. Syntax: [Link](key,
default). Example: [Link]('name', 'Unknown'). Unlike d['key'], doesn't raise KeyError.
Useful for safe access.
Q77: What are dictionary methods?
Answer: Common methods: keys() (all keys), values() (all values), items() (key-value
pairs), get(), pop(), update(), clear(), copy(). Iteration: for key in dict, for key, value in
[Link]().
Q78: How do you merge dictionaries?
Answer: Merge methods: [Link](d2) modifies d1, {**d1, **d2} creates new dict, d1 |
d2 (Python 3.9+). Later values override earlier for duplicate keys. Example: {**{'a':1},
**{'b':2}} = {'a':1, 'b':2}.
Q79: What is enumerate()?
Answer: enumerate() adds counter to iterable. Returns enumerate object of (index,
element) pairs. Syntax: enumerate(iterable, start=0). Example: for i, val in
enumerate(['a','b']): print(i, val) prints 0 a, 1 b.
Q80: What is zip()?
Answer: zip() combines multiple iterables element-wise. Returns zip object of tuples.
Example: list(zip([1,2], ['a','b'])) = [(1,'a'), (2,'b')]. Stops at shortest iterable. Useful for
parallel iteration.
Page 10 of 28
Python Interview Questions & Answers
Q81: What is the any() function?
Answer: any() returns True if any element is truthy. Example: any([0, False, 5]) returns
True. any([]) returns False. Short-circuits on first True. Useful with generators: any(x > 10
for x in nums).
Q82: What is the all() function?
Answer: all() returns True if all elements are truthy. Example: all([1, True, 'a']) returns
True. all([1, 0, 2]) returns False. all([]) returns True. Short-circuits on first False.
Q83: What is the max() and min() function?
Answer: max() returns largest element, min() returns smallest. Work with iterables or
multiple arguments. Optional key parameter for custom comparison. Example:
max([1,5,3]) = 5, max('a','z') = 'z', max(words, key=len).
Q84: What is the sum() function?
Answer: sum() returns total of iterable elements. Optional start value (default 0).
Example: sum([1,2,3]) = 6, sum([1,2,3], 10) = 16. Only works with numbers. For strings,
use ''.join().
Q85: What is the abs() function?
Answer: abs() returns absolute value of number. Works with int, float, complex.
Example: abs(-5) = 5, abs(-3.14) = 3.14, abs(3+4j) = 5.0 (magnitude of complex). Useful
for distance calculations.
Q86: What is the round() function?
Answer: round() rounds number to specified decimals. Syntax: round(number, ndigits).
Example: round(3.7) = 4, round(3.14159, 2) = 3.14. Uses banker's rounding (round half
to even).
Q87: What is the pow() function?
Answer: pow(x, y) returns x raised to power y. pow(x, y, z) returns (x**y) % z efficiently.
Example: pow(2, 3) = 8, pow(2, 3, 5) = 3. Third argument only for integers.
Q88: What is the divmod() function?
Answer: divmod() returns tuple of quotient and remainder. Syntax: divmod(a, b) = (a//b,
a%b). Example: divmod(17, 5) = (3, 2). Useful when you need both quotient and
remainder.
Q89: What is the ord() and chr() function?
Answer: ord() returns Unicode code point of character. chr() returns character from code
point. Example: ord('A') = 65, chr(65) = 'A'. Useful for character manipulation, encoding
work.
Q90: What is the id() function?
Answer: id() returns unique identifier (memory address) of object. Used to check if two
references point to same object. Example: a = [1,2]; b = a; id(a) == id(b) is True.
Page 11 of 28
Python Interview Questions & Answers
Q91: What is the isinstance() function?
Answer: isinstance() checks if object is instance of class/type. Syntax: isinstance(obj,
type). Example: isinstance(5, int) = True, isinstance('a', (str, int)) = True. Preferred over
type() for type checking.
Q92: What is the dir() function?
Answer: dir() returns list of attributes and methods of object. Without argument, returns
names in current scope. Useful for exploration and debugging. Example: dir([]) shows list
methods like append, pop, etc.
Q93: What is the help() function?
Answer: help() displays documentation for object, function, module. Example:
help(print), help([Link]). In interactive mode, help() starts help utility. Shows
docstrings and usage information.
Q94: What is a global variable?
Answer: Global variable is defined outside functions, accessible everywhere. To modify
inside function, use 'global' keyword. Example: x = 10 (global); def func(): global x; x =
20. Avoid excessive globals.
Q95: What is a local variable?
Answer: Local variable is defined inside function, only accessible within that function.
Created when function runs, destroyed when function ends. Parameters are local
variables. Can shadow global variables.
Q96: What is the global keyword?
Answer: global keyword declares variable inside function refers to global scope. Without
it, assignment creates new local variable. Example: def func(): global x; x = 10. Use
sparingly, prefer return values.
Q97: What is the nonlocal keyword?
Answer: nonlocal keyword references variable in enclosing function scope (not global).
Used in nested functions. Example: def outer(): x = 1; def inner(): nonlocal x; x = 2.
Introduced in Python 3.
Q98: What is recursion?
Answer: Recursion is a function calling itself. Requires base case to stop. Example: def
factorial(n): if n <= 1: return 1; return n * factorial(n-1). Elegant for certain problems but
watch for stack overflow.
Q99: What is the ternary operator in Python?
Answer: Ternary operator is conditional expression: value_if_true if condition else
value_if_false. Example: result = 'even' if x%2==0 else 'odd'. Concise alternative to if-
else for simple conditions.
Page 12 of 28
Python Interview Questions & Answers
PART 2: HARD QUESTIONS
Advanced Concepts, Internals, Metaclasses & Design Patterns
Q1: Explain Python's GIL (Global Interpreter Lock).
Answer: GIL is a mutex that allows only one thread to execute Python bytecode at a
time in CPython. It simplifies memory management but limits multi-threaded CPU-bound
performance. Workarounds: multiprocessing for CPU-bound tasks, asyncio for I/O-bound
tasks, or alternative interpreters like Jython, PyPy.
Q2: What are Python decorators and how do they work?
Answer: Decorators are functions that modify behavior of other functions/classes. They
wrap a function, adding functionality before/after. Syntax: @decorator above function
definition. Implementation: def decorator(func): def wrapper(*args, **kwargs): ... return
func(*args, **kwargs); return wrapper. Common uses: logging, authentication,
memoization.
Q3: Explain the difference between @staticmethod and @classmethod.
Answer: @staticmethod doesn't receive implicit first argument, behaves like regular
function but belongs to class namespace. @classmethod receives class (cls) as first
argument, can access/modify class state. Use staticmethod for utility functions,
classmethod for factory methods or alternative constructors.
Q4: What are metaclasses in Python?
Answer: Metaclasses are 'classes of classes' that define how classes behave. Classes
are instances of metaclasses (default: type). Create custom metaclass by inheriting from
type and overriding __new__ or __init__. Used for: class registration, API enforcement,
ORMs (like Django models), ABCs.
Q5: Explain Python's descriptor protocol.
Answer: Descriptors are objects implementing __get__, __set__, and/or __delete__
methods. They customize attribute access. Data descriptors (define __set__) take
precedence over instance dict. Non-data descriptors don't. Used internally for properties,
methods, staticmethods, classmethods. Enables computed attributes, validation, lazy
loading.
Q6: What is the MRO (Method Resolution Order)?
Answer: MRO is the order Python searches for methods in inheritance hierarchy. Uses
C3 linearization algorithm ensuring: children before parents, order preserved, common
ancestor last. View with Class.__mro__ or [Link](). Crucial for understanding
multiple inheritance behavior and super() calls.
Q7: Explain generators and the yield keyword.
Answer: Generators are functions using yield instead of return. They produce values
lazily, maintaining state between calls. yield pauses function, returns value; next()
resumes. Memory efficient for large sequences. Generator expressions: (x for x in
range(10)). Support send(), throw(), close() for advanced control.
Q8: What is the difference between __new__ and __init__?
Page 13 of 28
Python Interview Questions & Answers
Answer: __new__ creates the instance (static method, receives class). __init__
initializes the instance (receives self). __new__ returns instance; if not, __init__ isn't
called. Override __new__ for immutable types, singletons, or custom instance creation.
__new__ runs before __init__.
Page 14 of 28
Python Interview Questions & Answers
Q9: Explain Python's memory management.
Answer: Python uses reference counting (immediate deallocation when count hits 0)
plus cyclic garbage collector (handles reference cycles). Memory pools (pymalloc)
manage small objects. Object-specific free lists cache common types. Weak references
allow access without increasing ref count. Use gc module for control.
Q10: What are context managers and how do you create one?
Answer: Context managers handle setup/teardown via __enter__ and __exit__
methods. Used with 'with' statement. __exit__ receives exception info, can suppress by
returning True. Create using class with methods or @contextmanager decorator with
yield. Example: file handling, locks, database connections, timing.
Q11: Explain the asyncio library and async/await.
Answer: asyncio provides infrastructure for single-threaded concurrent code using
coroutines. async def defines coroutine, await pauses until awaitable completes. Event
loop manages execution. Benefits: efficient I/O, thousands of concurrent connections.
Key concepts: coroutines, tasks, futures, event loops. Use for I/O-bound, high-
concurrency applications.
Q12: What is the difference between concurrency and parallelism in Python?
Answer: Concurrency: multiple tasks make progress, potentially interleaved (asyncio,
threading). Parallelism: tasks execute simultaneously on multiple cores
(multiprocessing). GIL prevents true parallelism with threads for CPU-bound tasks. Use
asyncio for I/O-bound concurrency, multiprocessing for CPU-bound parallelism,
threading for I/O with simpler API.
Q13: Explain the __slots__ mechanism.
Answer: __slots__ declares fixed set of attributes, preventing __dict__ creation.
Benefits: memory savings (no dict per instance), faster attribute access, prevents
accidental attribute creation. Limitations: no dynamic attributes, must be defined in class
not inherited (unless parent also uses slots), complex with multiple inheritance.
Q14: What are Python closures?
Answer: Closures are nested functions that capture variables from enclosing scope. The
inner function 'closes over' outer variables, retaining access after outer function returns.
Variables are late-binding (evaluated at call time). Use for: function factories, decorators,
callbacks, data encapsulation. Access captured vars via func.__closure__.
Q15: Explain the difference between deepcopy and shallow copy.
Answer: Shallow copy ([Link]) creates new container but references same nested
objects. Deep copy ([Link]) recursively copies all nested objects. Example:
shallow copy of [[1,2],[3,4]] shares inner lists. Deepcopy handles circular references.
Custom copying via __copy__ and __deepcopy__ methods.
Q16: What is monkey patching?
Answer: Monkey patching is dynamically modifying classes or modules at runtime.
Example: replacing method with mock for testing, adding functionality to third-party code.
Risks: fragile, hard to debug, breaks encapsulation, may cause conflicts. Use cautiously,
prefer composition or subclassing when possible.
Page 15 of 28
Python Interview Questions & Answers
Q17: Explain Python's data model (dunder methods).
Answer: Data model defines special methods (__method__) for customizing object
behavior. Categories: construction (__new__, __init__), representation (__str__,
__repr__), comparison (__eq__, __lt__), arithmetic (__add__, __mul__), containers
(__len__, __getitem__), callables (__call__), context managers (__enter__, __exit__).
Enables operator overloading and Python integration.
Q18: What is duck typing?
Answer: Duck typing focuses on what object can do, not what it is. 'If it walks like a duck
and quacks like a duck, it's a duck.' Check behavior not type. Example: any object with
__iter__ is iterable. Promotes flexibility but may cause runtime errors. Use ABCs or
protocols for better structure.
Q19: Explain Abstract Base Classes (ABCs).
Answer: ABCs (abc module) define interfaces that subclasses must implement. Use
@abstractmethod for required methods. Cannot instantiate ABC directly. Supports virtual
subclassing via register(). Built-in ABCs in [Link] (Iterable, Sequence,
Mapping). Use for: enforcing APIs, type hints, isinstance checks without inheritance.
Q20: What are Python type hints and how do they work?
Answer: Type hints (PEP 484) annotate expected types. Syntax: def func(x: int) -> str.
Not enforced at runtime (use mypy for static checking). typing module provides generics
(List[int]), unions (Union[int, str]), Optional, Callable, TypeVar. Benefits: documentation,
IDE support, error detection, refactoring safety.
Q21: Explain the __call__ method.
Answer: __call__ makes instances callable like functions. Example: obj() invokes
obj.__call__(). Used for: stateful functions, decorators as classes, functors, factory
patterns. Useful when function needs to maintain state between calls or needs additional
methods.
Q22: What is the __getattr__ and __getattribute__ difference?
Answer: __getattribute__ called for EVERY attribute access, can easily cause infinite
recursion. __getattr__ called only when attribute NOT found normally. __getattr__ is
safer fallback. To access attrs in __getattribute__, use object.__getattribute__(self,
name). Used for: proxies, lazy loading, logging, dynamic attributes.
Q23: Explain iterators and the iterator protocol.
Answer: Iterator protocol requires __iter__ (returns self) and __next__ (returns next
value or raises StopIteration). Iterables have __iter__ returning iterator. Example: for
loop calls iter() then next() until StopIteration. Iterators are single-use, maintain position
state. Memory efficient for large sequences.
Q24: What is the difference between is and == for comparing objects?
Answer: 'is' checks identity (same object in memory, id()). '==' checks equality (value
comparison via __eq__). Use 'is' for None/True/False checks and singleton
comparisons. Use '==' for value comparison. Example: [1] == [1] is True, [1] is [1] is
False (different objects).
Page 16 of 28
Python Interview Questions & Answers
Q25: Explain Python's garbage collection.
Answer: Python uses reference counting (primary) plus cyclic garbage collector
(handles cycles). gc module controls collector. Three generations (0,1,2) with different
thresholds. Cycles detected periodically. Objects with __del__ may prevent collection
(improved in Python 3). Weak references (weakref) allow access without preventing
collection.
Q26: What are coroutines in Python?
Answer: Coroutines are functions that can pause execution and resume later. Old-style:
generator-based with yield. New-style: async def with await. Used for cooperative
multitasking, async I/O. Coroutines don't run until awaited or scheduled. [Link]()
starts event loop. Unlike threads: cooperative, single-threaded, explicit suspension
points.
Q27: Explain the descriptor __set_name__ method.
Answer: __set_name__(self, owner, name) is called when descriptor assigned to class
attribute. Receives owning class and attribute name. Useful for: automatic naming,
registration, validation setup. Added in Python 3.6. Example: storing attribute name for
better error messages or automatic database column naming.
Q28: What is the walrus operator (:=)?
Answer: Walrus operator (Python 3.8+) assigns values within expressions. Syntax:
name := expression. Useful in: while loops (while (line := [Link]())), list
comprehensions with filtering on computed value, conditional expressions. Reduces
repeated computation and intermediate variables. Use judiciously for readability.
Q29: Explain Python's import system in detail.
Answer: Import system: 1) Check [Link] cache, 2) Find module (finders in
sys.meta_path), 3) Load module (loaders). Search path: [Link] (current dir,
PYTHONPATH, site-packages). Packages need __init__.py (implicit in Python 3.3+).
Circular imports work if not at module level. __import__() is underlying function.
Q30: What are Python namespace packages?
Answer: Namespace packages (PEP 420) are packages without __init__.py, allowing
split across multiple directories. Portions in different locations combine into single
package. Useful for: large projects, plugin architectures, organization-wide packages.
Import system scans all [Link] entries. Different from regular packages in initialization
timing.
Q31: Explain the Global Interpreter Lock implementation details.
Answer: GIL is implemented as OS mutex in CPython. Threads acquire GIL, execute N
bytecode instructions (check interval), then release. I/O operations release GIL. C
extensions can release GIL for CPU-intensive work. Single GIL per interpreter
(subinterpreters have own GIL in 3.12+). Alternatives: Jython, IronPython have no GIL.
Q32: What is the __prepare__ method in metaclasses?
Answer: __prepare__(metacls, name, bases) returns namespace dict for class body
execution. Called before class body runs. Default returns empty dict. Override to return
OrderedDict (preserve attribute order), chainmap, or custom mapping. Useful for:
attribute ordering, preventing duplicate definitions, custom behavior during class
creation.
Page 17 of 28
Python Interview Questions & Answers
Page 18 of 28
Python Interview Questions & Answers
Q33: Explain Python's attribute lookup order.
Answer: Lookup order: 1) Data descriptors from type(obj).__mro__, 2) Instance
__dict__, 3) Non-data descriptors and class attributes from type(obj).__mro__, 4)
__getattr__ if defined. __getattribute__ controls entire process. Understanding crucial
for: descriptors, properties, custom attribute access, debugging inheritance issues.
Q34: What is the difference between __str__ and __repr__?
Answer: __repr__ is for developers (unambiguous, ideally eval-able), called by repr()
and debugger. __str__ is for users (readable), called by str() and print(). If __str__ not
defined, __repr__ used. Convention: __repr__ returns 'ClassName(args)', __str__
returns human-friendly string.
Q35: Explain the concept of Python protocols (structural subtyping).
Answer: Protocols ([Link], PEP 544) define interfaces via structural subtyping
(duck typing with type checking). Classes satisfying protocol methods are considered
subtypes without explicit inheritance. Used by mypy for static checking. Example: class
Drawable(Protocol): def draw(self) -> None: ... Any class with draw() matches.
Q36: What is the __init_subclass__ method?
Answer: __init_subclass__(cls, **kwargs) is called when class is subclassed. Receives
new subclass, not parent. Alternative to metaclasses for simpler cases. Useful for:
registration, validation, automatic attribute setup in subclasses. Keyword arguments
passed from class definition. Cleaner than __init_subclass__ in metaclass.
Q37: Explain Python's data classes.
Answer: @dataclass decorator (Python 3.7+) auto-generates __init__, __repr__,
__eq__, optionally __hash__, comparison methods. Parameters: frozen (immutable),
order (comparison), slots (use __slots__). field() customizes defaults, factory, repr
inclusion. Inheritance supported. Cleaner alternative to namedtuple for data containers.
Q38: What is the difference between multiprocessing and threading?
Answer: Threading: shared memory, GIL limits CPU-bound parallelism, lower overhead,
best for I/O-bound. Multiprocessing: separate memory spaces, true parallelism, higher
overhead (IPC needed), best for CPU-bound. Multiprocessing avoids GIL via separate
interpreters. Use Queue, Pipe, shared memory (Value, Array) for communication.
Q39: Explain Python's functools module utilities.
Answer: functools provides higher-order function utilities. lru_cache: memoization with
LRU eviction. partial: freeze some function arguments. reduce: cumulative operation.
wraps: preserve decorated function metadata. singledispatch: generic functions by type.
total_ordering: generate comparison methods. cached_property: lazy computed attribute
with caching.
Q40: What is the __class_getitem__ method?
Answer: __class_getitem__(cls, item) enables subscripting on classes (Class[item]).
Returns parameterized type. Used by generics: List[int], Dict[str, int]. Called when
subscripting class, not instance. Introduced for type hints, useful for generic class
implementations. Different from __getitem__ (instance subscripting).
Page 19 of 28
Python Interview Questions & Answers
Q41: Explain the collections module's specialized containers.
Answer: collections provides: namedtuple (tuple with names), deque (double-ended
queue, O(1) both ends), Counter (element counting), OrderedDict (insertion order, now
default dict behavior), defaultdict (default factory for missing keys), ChainMap (multiple
dict view). Use for: specific data structure needs, cleaner code.
Q42: What is the __hash__ method and its contract with __eq__?
Answer: __hash__ returns integer for hash-based containers (dict, set). Contract: if a ==
b, then hash(a) == hash(b) (converse not required). Mutable objects shouldn't be
hashable. If you define __eq__, must define __hash__ (or set to None for unhashable).
Default: id-based. Override for value-based equality.
Q43: Explain the weakref module.
Answer: weakref creates references that don't prevent garbage collection. ref() creates
weak reference (must call to access object). WeakValueDictionary, WeakKeyDictionary
for caches. WeakSet for collections. Callback on deletion. finalize() for destructor-like
behavior. Use for: caches, observers, avoiding circular references.
Q44: What is the difference between __del__ and context managers?
Answer: __del__ is destructor, called when reference count hits 0 (timing unpredictable,
may never run). Context managers (__enter__/__exit__) have deterministic timing with
'with' statement. Prefer context managers for resource cleanup. __del__ issues: circular
references, exception handling, interpreter shutdown order.
Q45: Explain Python's struct module.
Answer: struct packs/unpacks binary data using format strings. pack(fmt, values)
creates bytes, unpack(fmt, buffer) extracts values. Format codes: 'i' (int), 'f' (float), 's'
(string), etc. Byte order prefixes: '<' (little), '>' (big), '!' (network). Use for: binary file
formats, network protocols, C interoperability.
Q46: What is the __mro_entries__ method?
Answer: __mro_entries__(self, bases) allows non-class objects in class bases. Returns
tuple of classes for MRO calculation. Used by typing generics (List[int] in bases). Called
during class creation. Enables: generic aliases as bases, custom base transformations,
DSL-style class definitions.
Q47: Explain the contextlib module utilities.
Answer: contextlib provides context manager utilities. @contextmanager: create CM
from generator. suppress: ignore specified exceptions. redirect_stdout/stderr: redirect
output. nullcontext: no-op CM. ExitStack: programmatically manage multiple CMs.
closing: CM from object with close(). Use for cleaner resource management.
Q48: What is the inspect module used for?
Answer: inspect provides introspection: getmembers (attributes), signature (function
parameters), getsource (source code), getfile (filename), stack/trace (call stack),
isfunction/isclass/ismethod (type checks). Used for: debugging, documentation
generation, decorators, serialization, metaprogramming. Parameter info via
signature().parameters.
Page 20 of 28
Python Interview Questions & Answers
Q49: Explain Python's pickle module and its security implications.
Answer: pickle serializes Python objects to bytes. Handles most types, circular
references. Protocol versions (0-5) trade compatibility vs efficiency. Security: NEVER
unpickle untrusted data (arbitrary code execution via __reduce__). Use for: caching, IPC
between trusted processes. Alternatives: JSON, marshal (limited types), dill (extended
pickle).
Q50: What is the __reduce__ method?
Answer: __reduce__ controls how object is pickled. Returns callable and args to
reconstruct object. __reduce_ex__ takes protocol version. Used for: custom serialization,
singleton pickling, handling unpickleable attributes. Security risk: arbitrary code
execution on unpickle. Also __getstate__/__setstate__ for state control.
Q51: Explain the operator module.
Answer: operator provides function versions of operators. itemgetter: extract items
(sorted(data, key=itemgetter(1))). attrgetter: extract attributes. methodcaller: call
methods. add, mul, etc.: operator functions. Benefits: faster than lambdas, works with
pickle, cleaner for functional programming. Use with map, sorted, reduce.
Q52: What is the difference between exec() and eval()?
Answer: eval() evaluates single expression, returns result. exec() executes statements,
returns None. Both take code string and optional globals/locals. Security risk: never with
untrusted input. compile() for repeated execution. ast.literal_eval() safely evaluates literal
expressions. eval limited to expressions, exec handles any code.
Q53: Explain Python's threading synchronization primitives.
Answer: threading provides: Lock (mutual exclusion), RLock (reentrant lock),
Semaphore (limited access), BoundedSemaphore (error on too many releases), Event
(flag for signaling), Condition (wait/notify), Barrier (synchronization point). Use with
context managers. Lock prevents race conditions, Condition for producer-consumer
patterns.
Q54: What is the __annotations__ attribute?
Answer: __annotations__ dict holds type hints. Function annotations in
func.__annotations__, class annotations in Class.__annotations__. Runtime accessible,
not enforced. typing.get_type_hints() resolves forward references and string annotations.
PEP 563 (future annotations) delays evaluation. Use for: documentation, validation,
serialization.
Q55: Explain the typing module's advanced features.
Answer: Advanced typing: TypeVar (generics), Generic (generic base), Protocol
(structural subtyping), Literal (specific values), TypedDict (dict with typed keys), Final
(non-overridable), overload (multiple signatures), cast (type assertion),
TYPE_CHECKING (import guard). NewType for distinct types. ParamSpec for decorator
typing.
Q56: What is the __class__ attribute and its mutability?
Answer: __class__ references object's type. Assignable in Python (change object's
class at runtime). Restrictions: layout must be compatible (same __slots__, C extension
types). Use for: testing, proxies, dynamic class changes. Unusual but legal. Example:
obj.__class__ = NewClass migrates object to different class.
Page 21 of 28
Python Interview Questions & Answers
Page 22 of 28
Python Interview Questions & Answers
Q57: Explain Python's abstract syntax tree (AST) module.
Answer: ast parses Python code into tree structure. parse() creates AST,
NodeVisitor/NodeTransformer for traversal/modification, compile() to code object. Use
for: static analysis, code transformation, linting, macros, optimization. Each node
represents language construct. literal_eval safely evaluates literals. dump() for
inspection.
Q58: What is the __subclasshook__ method?
Answer: __subclasshook__(cls, C) in ABCs customizes isinstance/issubclass checks.
Return True (match), False (no match), or NotImplemented (normal check). Enables
structural subtyping: register virtual subclasses based on interface. Example: check if
class has required methods without inheritance.
Q59: Explain the difference between __contains__ and __iter__.
Answer: __contains__(self, item) handles 'in' operator, returns bool. __iter__ returns
iterator for iteration. 'in' checks: __contains__ if defined, else iterates via __iter__.
Defining __contains__ can optimize membership testing (O(1) for sets vs O(n) iteration).
Both enable 'in' operator differently.
Q60: What is the selectors module?
Answer: selectors provides high-level I/O multiplexing. Abstracts select, poll, epoll,
kqueue. DefaultSelector chooses best for platform. Register file objects with events
(READ, WRITE), select() returns ready ones. Foundation for asyncio. Use for: network
servers, non-blocking I/O, event-driven programming without asyncio.
Q61: Explain the __reversed__ method.
Answer: __reversed__ returns reverse iterator. Called by reversed() built-in. Default:
reversed() uses __len__ and __getitem__. Define for: efficient reverse iteration, custom
sequences. Generator-based implementation memory efficient. Example: def
__reversed__(self): for i in range(len(self)-1, -1, -1): yield self[i].
Q62: What is the __format__ method?
Answer: __format__(self, format_spec) customizes format(obj, spec) and f-strings.
format_spec is string after colon in format. Return formatted string. Example: datetime
uses %Y-%m-%d style, numbers use .2f style. Enable custom formatting languages for
your classes. Default calls __str__.
Q63: Explain Python's dis module.
Answer: dis disassembles Python bytecode. [Link]() shows bytecode instructions.
Useful for: optimization, understanding Python internals, debugging. Instructions:
LOAD_FAST, STORE_NAME, CALL_FUNCTION, etc. Each has opcode, argument, line
number. Bytecode changes between versions. Use to understand performance
implications.
Q64: What is the __missing__ method for dictionaries?
Answer: __missing__(self, key) called by dict.__getitem__ when key not found. Only
works if subclassing dict directly. Return value for missing key or raise exception.
[Link] uses this. Different from __getitem__: specifically for missing keys
in dict subclasses. Enables default factories, auto-vivification.
Page 23 of 28
Python Interview Questions & Answers
Q65: Explain the sys module's important attributes.
Answer: sys provides interpreter access: path (module search), modules (loaded
modules cache), argv (command-line args), stdin/stdout/stderr, version/version_info,
platform, executable, getrefcount(), getsizeof(), setrecursionlimit(), exc_info() (exception
info), exit(). Essential for: debugging, configuration, introspection.
Q66: What is the __bool__ method?
Answer: __bool__ defines truth value. Called by bool(), if statements, while, etc. Return
True or False. If not defined, __len__ != 0 used. If neither, always True. Example: empty
container returns False. Define for: logical evaluation, empty checks, validation states.
Preferred over __nonzero__ (Python 2).
Q67: Explain the difference between composition and inheritance.
Answer: Inheritance: 'is-a' relationship, subclass extends parent. Composition: 'has-a'
relationship, class contains other objects. Composition preferred for: flexibility, avoiding
deep hierarchies, mixing behaviors. Inheritance for: true type relationships, framework
requirements. 'Favor composition over inheritance' for maintainable code.
Q68: What is the __sizeof__ method?
Answer: __sizeof__ returns object's memory size in bytes (just the object, not
referenced objects). Called by [Link](). Default from object. Override for: custom
memory reporting, objects with external memory. [Link]() adds garbage collector
overhead. For deep size, use third-party libraries.
Q69: Explain the traceback module.
Answer: traceback handles exception tracebacks. print_exc() prints current exception,
format_exc() returns as string, extract_tb() gets frame info. TracebackException for
detailed handling. Use for: logging, custom error handling, debugging tools. Walk
traceback with tb_next, frames with tb_frame. Useful in except blocks.
Q70: What is the __await__ method?
Answer: __await__ makes object awaitable in async code. Returns iterator (usually self
from __iter__). Coroutines have built-in __await__. Custom awaitables: define __await__
returning iterator yielding to event loop. Used for: custom async primitives, wrapping
callbacks, async resource management. Enables 'await obj'.
Q71: Explain the enum module.
Answer: enum provides Enum, IntEnum, Flag, auto(). Members are singleton instances.
Access: [Link], Color['RED'], Color(1). IntEnum for int compatibility. Flag for bitwise
operations. @unique ensures no duplicates. auto() for automatic values. Benefits: type
safety, self-documenting, IDE support. Iterate, compare, use in dicts/sets.
Q72: What is the __subclasses__ method?
Answer: __subclasses__() returns list of direct subclasses. Only immediate children, not
descendants. Weak references: subclasses may disappear if not referenced. Use for:
plugin discovery, class registration, factory patterns. Recursive call needed for all
descendants. Note: may miss classes if garbage collected.
Page 24 of 28
Python Interview Questions & Answers
Q73: Explain the logging module architecture.
Answer: logging has: Loggers (hierarchical namespaces), Handlers (output
destinations), Formatters (message format), Filters (selective processing). Root logger is
parent. Levels: DEBUG, INFO, WARNING, ERROR, CRITICAL. Configure via
basicConfig, dictConfig, or programmatically. Use for: debugging, monitoring, audit trails.
Never print() in libraries.
Q74: What is the __bytes__ method?
Answer: __bytes__ returns bytes representation. Called by bytes(obj). Define for:
serialization, protocol encoding, binary representations. Different from __str__ (string)
and __repr__ (debug string). Example: return [Link]('utf-8'). Use for objects
that have natural bytes form.
Q75: Explain the copy protocol (__copy__ and __deepcopy__).
Answer: __copy__(self) implements shallow copy for [Link](). __deepcopy__(self,
memo) implements deep copy (memo dict tracks copied objects for circular references).
Return new instance. Default: uses __reduce__. Override for: custom copy behavior,
breaking cycles, lazy evaluation preservation. memo prevents infinite recursion.
Q76: What is the __set_name__ descriptor method?
Answer: __set_name__(self, owner, name) called when descriptor assigned to class
attribute. owner is containing class, name is attribute name. Automatic: don't need to
pass name to descriptor. Use for: self-documenting descriptors, automatic column
names in ORMs, validation error messages. Added Python 3.6.
Q77: Explain Python's match statement (structural pattern matching).
Answer: match statement (Python 3.10+) matches values against patterns. Patterns:
literal, capture, wildcard (_), sequence, mapping, class, OR (|), guard (if). Syntax: match
value: case pattern: action. More powerful than switch: destructuring, type matching,
nested patterns. Use for: state machines, parsers, complex conditionals.
Q78: What is the difference between [Link]() and [Link]()?
Answer: [Link]() checks pattern only at string START. [Link]() finds pattern
ANYWHERE in string. match('a', 'ba') fails, search('a', 'ba') succeeds. For whole string
match, use pattern with $ anchor or [Link](). search() more commonly needed.
Both return Match object or None.
Q79: Explain the itertools module.
Answer: itertools provides iterator building blocks. Infinite: count, cycle, repeat.
Terminating: chain, compress, dropwhile, takewhile, groupby, islice, starmap.
Combinatoric: product, permutations, combinations. chain.from_iterable for nested.
accumulate for cumulative. Memory efficient, lazy evaluation. Use for: data processing,
combinatorics, stream processing.
Q80: What is the __class_getitem__ vs __getitem__ difference?
Answer: __class_getitem__(cls, key) called when subscripting CLASS: List[int]. Returns
parameterized generic. __getitem__(self, key) called when subscripting INSTANCE:
obj[0]. Different purposes: class-level for types/generics, instance-level for container
access. __class_getitem__ is classmethod by default.
Page 25 of 28
Python Interview Questions & Answers
Q81: Explain the [Link] metaclass.
Answer: ABCMeta enables abstract base classes. @abstractmethod marks required
methods. @abstractproperty (deprecated, use @property + @abstractmethod). register()
adds virtual subclasses. __subclasshook__ customizes isinstance checks. Cannot
instantiate ABC with unimplemented abstracts. Multiple inheritance supported. Use for:
interfaces, contracts, frameworks.
Q82: What is the difference between __get__ with and without instance?
Answer: __get__(self, instance, owner) receives None for instance when accessed on
class ([Link]), actual object when on instance ([Link]). owner is always the class.
Use this to return different values: descriptor object for class access, computed value for
instance access. Function objects use this for method binding.
Q83: Explain the secrets module.
Answer: secrets provides cryptographically secure random numbers. token_bytes(n),
token_hex(n), token_urlsafe(n) for tokens. choice(), randbelow() for selection.
compare_digest() for timing-attack-safe comparison. Use for: passwords, tokens,
security-sensitive randomness. Different from random module (not secure). Required for:
auth tokens, password generation.
Q84: What is the __slots__ interaction with inheritance?
Answer: Slots in parent don't automatically apply to children. Child without __slots__
gets __dict__. Child with __slots__ adds to parent slots. Empty slots in child: __slots__ =
(). Complications: multiple inheritance with slots needs careful design, each class defines
own slots. Memory savings only if all classes in hierarchy use slots.
Q85: Explain the concept of coroutine delegation with yield from.
Answer: 'yield from' delegates to sub-generator. Handles: yielding values, sending
values, throwing exceptions, returning values. Cleaner than manual loop. Used in:
generator-based coroutines, refactoring generators. Returns sub-generator's return
value. Essential for async/await implementation. Introduced Python 3.3.
Q86: What is the __fspath__ protocol?
Answer: __fspath__ returns file system path (str or bytes). Called by [Link](). Path-
like objects implement this. [Link] implements it. Functions accepting paths call
[Link](). Use for: custom path classes, path wrappers. PEP 519 defines protocol.
Enables interop between path libraries and os/io functions.
Q87: Explain the difference between @property and descriptors.
Answer: @property creates descriptor using decorated methods (getter, setter, deleter).
Descriptors are general protocol (__get__, __set__, __delete__). property() is built-in
descriptor class. Custom descriptors: reusable across classes, more control, class-level
access. property: convenient, single-class. Descriptors underlie property, classmethod,
staticmethod.
Q88: What is the __module__ attribute?
Answer: __module__ stores name of module where class/function defined. For classes:
Class.__module__. For functions: func.__module__. Useful for: serialization, debugging,
documentation, logging. Qualified name: Class.__module__ + '.' + Class.__qualname__.
May be None for built-ins. Set automatically by class/def statement.
Page 26 of 28
Python Interview Questions & Answers
Q89: Explain the importlib module.
Answer: importlib provides programmatic imports. import_module(name) imports by
string. reload() reloads module. abc classes: Finder, Loader for custom import. resources
submodule accesses package files. metadata submodule gets package info. util has
spec helpers. Use for: plugins, lazy loading, dynamic imports, resource access.
Q90: What is the [Link] class?
Answer: Protocol (PEP 544) enables structural subtyping (static duck typing). Classes
matching method signatures are implicit subtypes. @runtime_checkable enables
isinstance checks. No explicit inheritance needed. Example: class Drawable(Protocol):
def draw(self) -> None: ... Mypy checks structurally. Use for: flexible interfaces, third-
party integration.
Q91: Explain the __matmul__ operator (@).
Answer: __matmul__ implements @ operator (matrix multiplication, PEP 465). Also
__rmatmul__ (right operand), __imatmul__ (in-place @=). Used by numpy for matrix
operations. Different from * (element-wise). Cleaner syntax for linear algebra. Example:
result = matrix1 @ matrix2. Define for: matrix classes, linear algebra types.
Q92: What is the difference between [Link] and pathlib?
Answer: [Link]: functions operating on path strings. pathlib: OOP interface, Path
objects. pathlib benefits: method chaining, operator overloading (/), cleaner API, type
safety. Path.read_text(), [Link](), [Link](). [Link] benefits: simpler, string-
based, legacy compatibility. pathlib preferred for new code. Convert: str(Path()) or
Path(string).
Q93: Explain the __instancecheck__ and __subclasscheck__ methods.
Answer: __instancecheck__(cls, instance) customizes isinstance().
__subclasscheck__(cls, subclass) customizes issubclass(). Defined on metaclass.
ABCMeta uses these for virtual subclasses. Return True/False/NotImplemented. Use for:
duck typing with type checks, protocol verification, custom type systems. Called by built-
in isinstance/issubclass.
Q94: What is the concept of cooperative multiple inheritance?
Answer: Cooperative inheritance uses super() correctly to call all parent methods. Each
class calls super(), following MRO. All classes must cooperate (accept **kwargs for
unknown args). Enables mixins and multiple inheritance without explicit parent calls.
Example: super().__init__(**kwargs) passes remaining args up chain. C3 linearization
ensures consistent order.
Page 27 of 28
Python Interview Questions & Answers
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Best of luck with your Python interviews!
Remember: Understand the concepts deeply, practice coding regularly,
and always think Pythonically!
Page 28 of 28