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 the @property decorator do in Python?

    @property turns a method into a read-only attribute, so obj.area calls the method without parentheses. Adding @name.setter lets you validate or compute on assignment while callers still use plain attribute syntax.

    IntermediateQuick answer1 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 is pathlib, and why is it preferred over os.path?

    pathlib represents file paths as objects, so you can join them with /, read their parts and read or write files through methods. It is more readable than string-based os.path calls and handles Windows and Linux separators for you.

    IntermediateQuick answer1 min read
  4. What is the difference between @classmethod, @staticmethod and an instance method?

    An instance method receives self, the object. A classmethod receives cls, the class, and is commonly used for alternative constructors. A staticmethod receives neither and is just a function living in the class namespace.

    IntermediateQuick answer1 min read
  5. 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
  6. What is the difference between absolute and relative imports in Python?

    An absolute import gives the full path from the project root, like from shop.billing import total. A relative import uses dots to start from the current package, like from .billing import total. Relative imports work only inside packages.

    IntermediateQuick answer1 min read
  7. What is the difference between EAFP and LBYL in Python?

    LBYL (look before you leap) checks conditions first, like if key in d. EAFP (easier to ask forgiveness than permission) just tries the operation and handles the exception. Python code usually prefers EAFP, especially where checking and acting could race.

    IntermediateQuick answer1 min read
  8. What is the difference between str and bytes in Python 3?

    str holds Unicode text, a sequence of characters. bytes holds raw 8-bit values. You encode a str to get bytes and decode bytes to get a str, and you must name the encoding, usually UTF-8.

    IntermediateQuick answer1 min read
  9. What is the difference between the global and nonlocal keywords in Python?

    global makes a name inside a function refer to the module-level variable. nonlocal makes it refer to a variable in the nearest enclosing function. Both are needed only when you assign to the name, not when you just read it.

    IntermediateQuick answer1 min read
  10. 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
  11. 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
  12. Why is "".join(list_of_strings) preferred over += inside a loop?

    Strings are immutable, so each += may copy the whole string built so far, which can become quadratic. join() computes the total size once and copies each piece a single time, so it runs in linear time.

    IntermediateQuick answer1 min read
  13. Why is a bare "except:" considered bad practice in Python?

    A bare except catches everything, including KeyboardInterrupt and SystemExit, so Ctrl+C stops working and real bugs get hidden. Catch specific exceptions, or at most "except Exception", and log or re-raise what you cannot handle.

    IntermediateQuick answer1 min read
  14. 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
  15. Write a function to transpose a matrix (swap its rows and columns).

    Use zip(*matrix) and convert each tuple to a list, or use a nested comprehension indexing matrix[r][c]. The first row becomes the first column. The time is O(rows x cols).

    IntermediateQuick answerCoding1 min read
  16. 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
  17. 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
  18. 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
  19. 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
  20. 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
  21. 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