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 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
  2. 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
  3. 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
  4. What does this function return when both try and finally have a return statement?

    It returns the value from the finally block. finally always runs last, and a return inside it overrides the earlier return and even discards a pending exception. This is why returning from finally is considered bad practice.

    AdvancedQuick answer1 min read
  5. 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