Interview Q&A / Python

INTERVIEW Q&A · 81 QUESTIONS

Python interview questions

Lists, dictionaries, generators, decorators and the Python questions asked in service-company and data roles.

  1. 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
  2. Write a generator that yields the first n Fibonacci numbers.

    Keep two variables a and b, yield a, then update them with a, b = b, a + b, repeating n times. The generator produces one value at a time, uses O(1) memory and does O(n) additions in total.

    BeginnerQuick answerCoding1 min read
  3. 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
  4. What does yield from do in Python?

    yield from iterable hands over each item of another iterable or generator to the caller, as if you had written a for loop with yield. It also passes through values sent into the generator and returns the sub-generator's return value.

    AdvancedQuick answer1 min read