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 decorator in Python and how do you write one?

    A decorator is a function that takes another function, wraps it with extra behaviour, and returns the wrapped version. Writing @my_decorator above a function is shorthand for func = my_decorator(func). They are used for logging, timing, caching and access checks without changing the original function's code.

    IntermediateIn-depth3 min read
  2. 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
  3. What does this print: a list of lambdas created in a loop, each returning i?

    All the lambdas print the last value of i. Closures capture the variable, not its value at creation time, and i is looked up when the lambda is called. Fix it with a default argument: lambda i=i: i.

    AdvancedQuick answer1 min read