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 →
- What is a generator in Python, and how is yield different from return?
A generator is a function that uses yield to produce values one at a time, pausing after each one and resuming where it left off on the next request. return ends the function and gives back one result, while yield hands out a value and keeps the function's state. Generators save memory because they never build the full list.
IntermediateIn-depth3 min read - What is the difference between an iterable and an iterator in Python?
An iterable can produce an iterator when you call iter() on it, such as a list or string. An iterator is the object that actually hands out items one at a time through next() and remembers its position. Iterators are single-use.
BeginnerQuick 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 - 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