Interview Q&A / Python
Python interview questions
Lists, dictionaries, generators, decorators and the Python questions asked in service-company and data roles.
Prefer rapid revision? Practise Python short interview answers →
- Does the loop variable of a list comprehension leak into the surrounding scope in Python 3?
No. In Python 3 a comprehension has its own scope, so its loop variable does not leak. A normal for loop does leave its variable behind. In Python 2, list comprehensions did leak.
IntermediateQuick answer1 min read - How do you make your own class work with +, len() and indexing in Python?
Implement the matching dunder methods: __add__ for +, __len__ for len(), and __getitem__ for obj[i]. Python translates the syntax into calls to these methods, so no inheritance from built-in types is needed.
IntermediateQuick answer1 min read - How do you read a very large file in Python without loading it all into memory?
Iterate over the file object directly with for line in f. It reads one line at a time through a buffer, so memory use stays small. read() and readlines() load everything at once and can exhaust memory on big files.
IntermediateQuick answer1 min read - How do you write your own context manager in Python?
Either write a class with __enter__ and __exit__ methods, or write a generator function decorated with @contextlib.contextmanager that yields once. Code before the yield is setup and code after it is cleanup, which should sit in a finally block.
IntermediateQuick answer1 min read - How does a for loop work under the hood in Python?
A for loop calls iter() on the object to get an iterator, then repeatedly calls next() on it, running the body each time. When next() raises StopIteration, the loop ends quietly.
IntermediateQuick answer1 min read - How does Python find a module when you write import?
Python checks sys.modules for an already-loaded copy, then searches the directories in sys.path in order: the script's folder, PYTHONPATH entries, the standard library and site-packages. The first match wins, which is why a local file can shadow a library.
IntermediateQuick answer1 min read - What are Decimal and Fraction in Python, and when would you use them instead of float?
Decimal does exact base-10 arithmetic, which suits money. Fraction stores a ratio of two integers and gives exact results for things like 1/3. Both avoid the binary rounding errors of float, at the cost of speed.
IntermediateQuick answer1 min read - What do the / and * markers in a Python function signature mean?
Parameters before / are positional-only, so callers cannot pass them by name. Parameters after a bare * are keyword-only, so callers must pass them by name. Both make an API clearer and safer to change.
IntermediateQuick answer1 min read - What does "from module import *" do, and what is __all__?
import * brings every public name of a module into your namespace, which can silently overwrite existing names. A module can control what it exports by defining __all__, a list of names. Without __all__, names starting with an underscore are skipped.
IntermediateQuick answer1 min read - What does super() do in Python, and why call super().__init__()?
super() returns a proxy that looks up methods on the next class in the MRO. Calling super().__init__() runs the parent's initialiser so the inherited setup is not skipped. If a child defines __init__ and does not call it, the parent's attributes are never created.
IntermediateQuick answer1 min read - What does the @property decorator do in Python?
@property turns a method into a read-only attribute, so obj.area calls the method without parentheses. Adding @name.setter lets you validate or compute on assignment while callers still use plain attribute syntax.
IntermediateQuick answer1 min read - What is a closure in Python?
A closure is an inner function that remembers variables from the enclosing function even after that outer function has finished. It is how Python implements function factories and decorators with private state.
IntermediateQuick answer1 min read - What is pathlib, and why is it preferred over os.path?
pathlib represents file paths as objects, so you can join them with /, read their parts and read or write files through methods. It is more readable than string-based os.path calls and handles Windows and Linux separators for you.
IntermediateQuick answer1 min read - What is the difference between @classmethod, @staticmethod and an instance method?
An instance method receives self, the object. A classmethod receives cls, the class, and is commonly used for alternative constructors. A staticmethod receives neither and is just a function living in the class namespace.
IntermediateQuick answer1 min read - What is the difference between a class attribute and an instance attribute, and what does this code print?
A class attribute is shared by all instances. An instance attribute belongs to one object. Assigning through an instance, like a.count = 5, creates a new instance attribute that shadows the class one, but mutating a shared list changes it for everyone.
IntermediateQuick answer1 min read - What is the difference between absolute and relative imports in Python?
An absolute import gives the full path from the project root, like from shop.billing import total. A relative import uses dots to start from the current package, like from .billing import total. Relative imports work only inside packages.
IntermediateQuick answer1 min read - What is the difference between EAFP and LBYL in Python?
LBYL (look before you leap) checks conditions first, like if key in d. EAFP (easier to ask forgiveness than permission) just tries the operation and handles the exception. Python code usually prefers EAFP, especially where checking and acting could race.
IntermediateQuick answer1 min read - What is the difference between str and bytes in Python 3?
str holds Unicode text, a sequence of characters. bytes holds raw 8-bit values. You encode a str to get bytes and decode bytes to get a str, and you must name the encoding, usually UTF-8.
IntermediateQuick answer1 min read - What is the difference between the global and nonlocal keywords in Python?
global makes a name inside a function refer to the module-level variable. nonlocal makes it refer to a variable in the nearest enclosing function. Both are needed only when you assign to the name, not when you just read it.
IntermediateQuick answer1 min read - Why does the second loop over a generator print nothing?
A generator is an iterator, so it can be consumed only once. After the first loop reaches the end, it is exhausted, and later loops or list() calls get no items. Create a new generator, or store the values in a list, to reuse them.
IntermediateQuick answer1 min read - Why does this code raise UnboundLocalError even though x is defined globally?
Assigning to x anywhere inside a function makes x local to the whole function. Reading it before the assignment then fails with UnboundLocalError. Declare global x, or pass x in as an argument, to fix it.
IntermediateQuick answer1 min read - Why is "".join(list_of_strings) preferred over += inside a loop?
Strings are immutable, so each += may copy the whole string built so far, which can become quadratic. join() computes the total size once and copies each piece a single time, so it runs in linear time.
IntermediateQuick answer1 min read - Why is a bare "except:" considered bad practice in Python?
A bare except catches everything, including KeyboardInterrupt and SystemExit, so Ctrl+C stops working and real bugs get hidden. Catch specific exceptions, or at most "except Exception", and log or re-raise what you cannot handle.
IntermediateQuick answer1 min read - Write a class that implements the iterator protocol to count down from n to 1.
Define __iter__ returning self and __next__ returning the next value, raising StopIteration when the countdown ends. Store the current position on the instance. Each next call is O(1) and the class uses O(1) space.
IntermediateQuick answerCoding1 min read - Write a function to transpose a matrix (swap its rows and columns).
Use zip(*matrix) and convert each tuple to a list, or use a nested comprehension indexing matrix[r][c]. The first row becomes the first column. The time is O(rows x cols).
IntermediateQuick answerCoding1 min read