Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Thursday, June 19, 2025

Interview Questions on "Arrays" - Ch 2 - Fluent Python

All Posts on Python

Interview Questions from "Fluent Python" Chapter 2: Sequences

Easy Questions

  1. What are the two main categories of sequences based on mutability?

  2. How do container sequences differ from flat sequences?

  3. What is the key advantage of list comprehensions over map/filter?

  4. How do you prevent list comprehensions from leaking variables (Python 2 vs. Python 3)?

  5. What is the purpose of collections.namedtuple?

  6. How does tuple unpacking work in Python?

  7. What does the * operator do in tuple unpacking (e.g., a, *rest = [1, 2, 3])?

  8. Why do Python slices exclude the last item (e.g., my_list[0:3])?

  9. How do you reverse a sequence using slicing?

  10. What is the difference between list.sort() and sorted()?


Medium Questions

  1. Explain how generator expressions save memory compared to list comprehensions.

  2. How would you use a list comprehension to generate a Cartesian product?

  3. When should you use bisect instead of the in operator for membership tests?

  4. How does bisect.insort maintain a sorted sequence efficiently?

  5. Why might array.array be preferable to list for numerical data?

  6. What is the purpose of memoryview in handling large datasets?

  7. How does deque.rotate() work, and when would you use it?

  8. What happens when you assign to a slice (e.g., my_list[2:5] = [20, 30])?

  9. Why does my_list = [[]] * 3 create a list with shared references?

  10. How does the key parameter in sorted() enable case-insensitive sorting?


Complex Questions

  1. Explain the behavior of a += b for mutable vs. immutable sequences.

  2. Why does t[2] += [50, 60] raise a TypeError but still modify a tuple’s mutable element?

  3. How does NumPy’s ndarray improve performance for numerical operations?

  4. Discuss the performance trade-offs of using deque vs. list for FIFO/LIFO operations.

  5. How can memoryview.cast() manipulate binary data without copying bytes?

  6. When would you use array.tofile() instead of pickle for saving numerical data?

  7. Explain how the key parameter in sorting functions leverages stability (e.g., Timsort).

  8. How does bisect support efficient table lookups (e.g., converting scores to grades)?

  9. Why is deque thread-safe for append/pop operations?

  10. Compare the performance of array.fromfile() vs. reading floats from a text file.


These questions cover core sequence operations, performance optimizations, and practical applications from the chapter, suitable for evaluating a candidate's depth of understanding.

Wednesday, June 18, 2025

What is the Python Data Model?

All Questions From This Chapter

The Python Data Model is the framework that defines how Python objects behave and interact with each other. It’s the foundation for all built-in behavior in Python, such as arithmetic operations, attribute access, iteration, string representation, and more.

🧩 Key Idea:

The Python Data Model is made up of special methods (a.k.a. "dunder" methods — methods with double underscores like __len__, __getitem__, __str__, etc.) that let you hook into the language’s syntax and built-in functions.


🔍 Examples of Special Methods and What They Enable:

MethodTriggered byUse Case
__len__len(obj)Make object countable
__getitem__obj[index]Indexing, slicing support
__iter__for item in objMake object iterable
__str__str(obj) or print(obj)Human-readable string representation
__repr__repr(obj)Debug-friendly object display
__call__obj()Make object behave like a function
__add__obj1 + obj2Operator overloading
__bool__if obj:Truthiness of an object

🎯 Why It Matters:

  • Lets you create custom classes that integrate seamlessly with Python’s built-in operations.

  • Powers frameworks like Django, Pandas, NumPy, and more.

  • Enables writing Pythonic, intuitive, and idiomatic code.


📘 Example:

python
class Word: def __init__(self, text): self.text = text def __len__(self): return len(self.text) def __str__(self): return f"Word: {self.text}" word = Word("Python") print(len(word)) # → 6 print(str(word)) # → Word: Python

📚 Summary:

The Python Data Model is what allows Python to be flexible, expressive, and powerful. It’s the secret sauce behind how user-defined classes can behave like built-in types.

Want to dive deeper into this? Luciano Ramalho's "Fluent Python" is an excellent book focused on this very concept.

Tags: Technology,Python,Interview Preparation,

What built-in function calls __abs__?

All Questions From This Chapter

The built-in function abs() in Python calls the __abs__ dunder method on an object.


✅ Example:

python
class Temperature: def __init__(self, value): self.value = value def __abs__(self): return abs(self.value) temp = Temperature(-40) print(abs(temp)) # Output: 40

🔍 What’s Happening:

When you write abs(temp), Python internally calls:

python
temp.__abs__()

This allows you to define custom behavior for abs() on your own classes.


🧠 Summary:

  • abs(obj) → Calls obj.__abs__()

  • You must implement __abs__ if you want your custom class to support abs()

This is part of Python’s data model that allows operator/function overloading.

Tags: Technology,Python,Interview Preparation,

What are "dunder" methods? Give an example.

All Questions From This Chapter

"Dunder" methods (short for "double underscore" methods) are special methods in Python that begin and end with double underscores (__), like __init__, __str__, and __len__. They’re also known as magic methods or special methods.

These methods are used to:

  • Customize the behavior of built-in operations

  • Enable operator overloading

  • Integrate your class with Python's core language features (like iteration, context managers, etc.)


Example:

python
class Book: def __init__(self, title): self.title = title def __str__(self): return f"Book: {self.title}" book = Book("Fluent Python") print(book) # Output: Book: Fluent Python
  • __init__: Initializes the object (like a constructor).

  • __str__: Defines what str(obj) or print(obj) returns.


🧠 Common Dunder Methods:

MethodPurpose
__init__Constructor (called on object creation)
__str__String representation (print(obj))
__repr__Debug representation (repr(obj))
__len__Length (len(obj))
__getitem__Indexing (obj[i])
__iter__Makes an object iterable
__eq__Equality (==)

Dunder methods let your objects behave like built-in types and integrate seamlessly with Python’s syntax and idioms.

Tags: Technology,Python,Interview Preparation,

What happens if you don’t implement __bool__ in a class?

All Questions From This Chapter

If you don’t implement __bool__ in a Python class, Python falls back to another method to determine the truthiness of your object.

🔁 Fallback Behavior:

  1. If __bool__ is not defined, Python checks for __len__.

  2. If __len__ is defined:

    • if obj: will evaluate to False if len(obj) == 0.

    • Otherwise, it evaluates to True.

  3. If neither __bool__ nor __len__ is defined, the object is considered truthy by default (i.e., True).


🔍 Example Without __bool__:

python
class Empty: def __len__(self): return 0 e = Empty() print(bool(e)) # False, because __len__ returns 0

🧱 Example With Neither:

python
class Thing: pass t = Thing() print(bool(t)) # True, because no __bool__ or __len__

✅ Summary

You define…bool(obj) is…
__bool__Uses the returned Boolean value
__len__, no __bool__False if len(obj) == 0, True otherwise
NeitherAlways True

🧠 Tip: Define __bool__ if you want explicit control over an object’s truthiness.

Tags: Technology,Python,Interview Preparation,