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 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
  2. 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
  3. 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
  4. What is a circular import in Python, and how do you fix it?

    A circular import happens when module A imports B while B imports A, so one of them is used before it is fully loaded, causing ImportError or AttributeError. Fix it by restructuring, moving the shared code to a third module, or importing inside the function.

    AdvancedQuick answer1 min read
  5. What is the Method Resolution Order (MRO) in Python, and how does it work with multiple inheritance?

    The MRO is the order in which Python searches a class and its parents for an attribute. It uses C3 linearization: children come before parents, and the order of bases you wrote is kept. You can see it with ClassName.__mro__ or mro().

    AdvancedQuick answer1 min read
  6. Why must you define __hash__ when you define __eq__ for objects used in sets or as dict keys?

    Objects that compare equal must have the same hash, or sets and dicts will treat them as different. Defining __eq__ without __hash__ sets __hash__ to None, so the class becomes unhashable. Base the hash on the same fields that __eq__ compares.

    AdvancedQuick answer1 min read