Wednesday, June 18, 2025

How can you make an object iterable in Python?

All Questions From This Chapter

Make an object iterable

To make an object iterable in Python, you need to implement either:


✅ Option 1: __iter__()

The simplest and most common way is to define an __iter__() method that returns an iterator (usually self or a generator).

Example:

python
class MyIterable: def __init__(self, data): self.data = data def __iter__(self): return iter(self.data) # delegates to the iterable data obj = MyIterable([1, 2, 3]) for item in obj: print(item)

✅ Option 2: __getitem__() (legacy approach)

If your object implements __getitem__() and raises IndexError when the sequence ends, it is implicitly iterable.

Example:

python
class MyIterable: def __init__(self, data): self.data = data def __getitem__(self, index): return self.data[index] obj = MyIterable([10, 20, 30]) for item in obj: print(item)

Python internally tries to call obj[0], obj[1], ... until IndexError is raised.


🧠 Summary:

MethodRequired?Purpose
__iter__()YesReturns an iterator for your object
__next__()OptionalNeeded if your class is also the iterator
__getitem__()LegacyAllows iteration without __iter__()

Best practice: Prefer __iter__() + generators for clean, efficient code.

Tags: Python,Interview Preparation,Technology,

How does __getitem__ enable sequence-like behavior in a class?

All Questions From This Chapter

__getitem__ to enable sequence-like behavior

The __getitem__ method enables sequence-like behavior in a Python class by allowing you to access items in the object using square bracket notation—just like you do with lists, tuples, or strings.


✅ What it does:

When you define __getitem__(self, key) in your class:

  • Python calls this method whenever you do obj[key]

  • You can support:

    • Indexing (obj[0])

    • Slicing (obj[1:4])

    • Even complex keys like tuples (obj[1, 2])


📦 Example:

python
class MySequence: def __init__(self, data): self.data = data def __getitem__(self, index): return self.data[index] seq = MySequence([10, 20, 30, 40]) print(seq[1]) # 20 print(seq[1:3]) # [20, 30]

🔁 What it enables:

  • Looping with for item in obj

  • Indexing and slicing

  • Compatibility with len(), in, enumerate(), etc. (if other methods like __len__ and __iter__ are also defined)


🧠 Summary:

Implementing __getitem__ turns your class into an indexable and iterable object, giving it familiar behavior like Python’s built-in sequences.

Tags: Technology,Python,Interview Preparation,

What is the purpose of __len__ in a Python class?

All Questions From This Chapter

__len__ in a Python class?

The purpose of __len__ in a Python class is to define how the built-in len() function should behave when called on an instance of that class.

Why it's used:

  • When you implement __len__, you're telling Python how to compute the "length" of your custom object.

Example:

python
class MyCollection: def __init__(self, items): self.items = items def __len__(self): return len(self.items) c = MyCollection([1, 2, 3]) print(len(c)) # Output: 3

Key Points:

  • __len__ must return an integer ≥ 0.

  • If __len__ is not defined, calling len() on the object will raise a TypeError.

It’s especially useful when creating custom container types that conceptually hold multiple items.

Tags: Python,Interview Preparation,Technology,

Interview Questions on "The Python Data Model" - Ch 1 - Fluent Python

All Posts on Python

Easy Questions

  1. What is the Python Data Model?

  2. Why does Python use len(collection) instead of collection.len()?
    Why is `len()` not a method in Python?

  3. What are "dunder" methods? Give an example.

  4. What is the purpose of __len__ in a Python class?

  5. How does __getitem__ enable sequence-like behavior in a class?

  6. What is the difference between __repr__ and __str__?

  7. Why is __repr__ important for debugging?

  8. How can you make an object iterable in Python?

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

  10. What built-in function calls __abs__?


Medium Questions

  1. Explain how FrenchDeck leverages the Python Data Model to support slicing and iteration.

  2. Why does random.choice work on FrenchDeck without any extra methods?

  3. How does __contains__ affect the behavior of the in operator?

  4. What is the role of collections.namedtuple in the FrenchDeck example?

  5. How would you modify FrenchDeck to make it shuffleable?

  6. Why should you avoid directly calling special methods like __len__?

  7. How does __add__ enable vector addition in the Vector class?

  8. Why does Vector.__bool__ check bool(abs(self)) instead of just self.x or self.y?

  9. What is the difference between __mul__ and __rmul__?

  10. How does Python determine the truth value of an object if __bool__ is not implemented?


Complex Questions

  1. How does Python’s handling of len() differ for built-in types vs. custom classes?

  2. Explain the concept of the "metaobject protocol" in Python.

  3. Why does the Vector class return a new instance in __add__ and __mul__ instead of modifying self?

  4. How could you extend the Vector class to support n-dimensional vectors?

  5. Discuss the trade-offs between using abs(self) vs. self.x or self.y in Vector.__bool__.

  6. What are "reversed operators" (e.g., __radd__), and when are they used?

  7. How does Python’s operator overloading compare to other languages like C++ or Java?

  8. Why does the Python Data Model avoid arbitrary "magic" method names like __foo__?

  9. How could you implement a context manager using __enter__ and __exit__?

  10. What are the performance implications of using special methods vs. direct method calls?


These questions cover fundamental concepts, practical implementations, and deeper design principles from the chapter, suitable for assessing a candidate’s understanding of Python’s Data Model.

Generated using DeepSeek (R1) from the chapter 1 of book "Fluent Python" by Luciano Ramalho Tags: Technology,Python,Interview Preparation,

Why is `len()` not a method in Python?

All Questions From This Chapter

Why does Python use len(collection) instead of collection.len()?

Great question! Python uses len(collection) instead of collection.len() primarily due to its design philosophy. Here's why:


🔹 1. Simplicity and Consistency (The Zen of Python)

Python follows the principle:

"There should be one– and preferably only one –obvious way to do it."

Having a standard function like len() that works across all built-in types (lists, strings, dicts, etc.) provides consistency.

python
len("hello") # 5 len([1, 2, 3]) # 3 len({'a': 1}) # 1

You don’t have to remember if it’s .size(), .length(), .count(), etc.


🔹 2. Uniform Interface for Built-ins and Custom Objects

len() is a built-in function that internally calls the special method __len__() on the object. This gives flexibility to customize behavior:

python
class MyList: def __len__(self): return 42 obj = MyList() print(len(obj)) # 42

If Python had used collection.len(), you'd need every class to implement that specific method name, and it wouldn’t be as universal.


🔹 3. Separation of Interface and Implementation

Using len(obj) separates the public interface (len) from the internal mechanics (__len__). This is more in line with Python’s philosophy of:

“We’re all consenting adults here.”


🔹 4. Easier to Use in Polymorphic Code

Since len() works with any object implementing __len__(), it allows for duck typing:

python
def print_length(x): print(len(x)) # Works for any x that defines __len__()

✅ Summary

Why len(x) is better than x.len()
More readable and consistent
Works across built-ins and user-defined types
Enables polymorphism via __len__()
Avoids inconsistent method names

So while x.len() might seem more "object-oriented," len(x) is more Pythonic.

Tags: Python,Interview Preparation,Technology,

Tuesday, June 17, 2025

Do I need to find a purpose in life? — Mingyur Rinpoche


All Book Summaries
Have you ever feel that I don't know how to do with my life? Yeah? Actually, you're not alone. Most people feel like that kind of feeling. And when we look around the most like society and the world normally expecting or forcing us to have great purpose, meaning of life. When we discuss with our friends, family and workplace, in the society, looks like everybody is forcing us, you need to find your own purpose. But most people not. So why is that? So, in our meditation traditional what we call "everything is impermanent". And "everything is interdependent", meaning cause and condition. Like for example, some scientists they find the greatest discovery. But this discovery is not there when they begin to look for those, right? So you just kind of like have many different ideas. And you try, do some experiment. Then you find something. Then you go forward. And at the same time life is up and down because of impermanent. What we call life is like wave of the ocean. But the most important thing is, we are more than what we believe. So actually you have what we call everybody has this basic innate goodness. So you have awareness, love and compassion, wisdom, skill potential capacity. So, the most important is be present be with you right now. And then follow the flow of life with use your own wisdom. Your own love, compassion, skills, try your best. But don't you tie on the result. So then maybe you can find the better meaning of life rather than forcing yourself that I need to find a single meaning and the perfect that is difficult. When you force something that thing disappears, right? So be here now be present and believe in yourself and try your best. But don't tie on the result. 
Tags: Buddhism,Video,Psychology,Motivation,