Back to Study Material Python

Interview Questions and Answers

This section covers deeper Python interview questions that go beyond syntax recall and test genuine understanding of how Python works under the hood. Q: W...

Interview Questions and Answers

In-Depth Python Interview Questions and Answers

This section covers deeper Python interview questions that go beyond syntax recall and test genuine understanding of how Python works under the hood.

Q: What are Python generators and why use them? A: Generators are functions that use yield instead of return. They produce values lazily, one at a time, rather than computing the entire sequence upfront. This saves memory when working with large data: def fibonacci(): a, b = 0, 1 while True: yield a a, b = b, a + b

gen = fibonacci() print([next(gen) for _ in range(10)]) # first 10 Fibonacci numbers

Q: What is the difference between @classmethod and @staticmethod? A: @classmethod receives the class (cls) as its first argument and can access or modify class-level state. @staticmethod receives no implicit first argument — it behaves like a plain function that lives inside the class for organizational purposes.

Q: What are Python descriptors? A: Descriptors are objects that define how attribute access works via __get__, __set__, and __delete__ methods. Properties (@property) are descriptors. They power the ORM attributes in Django.

Q: What is the difference between deep copy and shallow copy? A: A shallow copy (copy.copy) creates a new container but its elements are still references to the originals. A deep copy (copy.deepcopy) recursively copies all nested objects. Shallow copies are faster; deep copies are fully independent.

Q: How does Python's with statement work? A: It uses a context manager protocol: __enter__ runs when entering the block, __exit__ runs when leaving (even if an exception occurs). This guarantees cleanup: with open('file.txt', 'r') as f: data = f.read() # file is automatically closed here

Q: What is metaprogramming in Python? A: Writing code that creates or modifies other code at runtime. This includes decorators, metaclasses (__init_subclass__, __class_getitem__), and dynamic attribute access (getattr, setattr).

Q: Explain mutable default arguments pitfall. def append_to(element, to=[]): # BUG: list created once to.append(element) return to Fix: def append_to(element, to=None): to = to if to is not None else []

Practical tip: Study the Python Data Model (dunder methods). Understanding __len__, __getitem__, __iter__, __repr__, __eq__, and __hash__ enables writing idiomatic, Pythonic classes that integrate seamlessly with built-in functions.

Exam tip: Be ready to explain time complexity of common Python operations. List append: O(1) amortized. List insert at front: O(n). Dict lookup: O(1) average. Set membership: O(1) average. Sorting: O(n log n).