+91 81900 98289

Python __len__

This Python __len__ lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

__len__ lets len work on your object. Return a non-negative integer.

An empty collection should return 0, not None.

Example 1: Start here

bool uses __len__ when __bool__ is missing. A length of 0 is treated as false.

class Batch: # a template for objects def __init__(self, names): # runs when you create the object self.names = names # store this on the object def __len__(self): # define the function; it runs when you call it return len(self.names) # send this value back to the caller print(len(Batch(["Meera", "Arun"]))) # len counts the items

Example 2: len on a class

__len__ must return a non-negative integer.

class Roster: # a template for objects def __init__(self, names): # runs when you create the object self.names = names # store this on the object def __len__(self): # define the function; it runs when you call it return len(self.names) # send this value back to the caller print(len(Roster(["Asha", "Arun"]))) # len counts the items

Example 3: An empty roster

Zero is a valid length.

class Roster: # a template for objects def __init__(self): # runs when you create the object self.names = [] # store this on the object def __len__(self): # define the function; it runs when you call it return len(self.names) # send this value back to the caller print(len(Roster())) # len counts the items

Example 4: Use it in an if

A container is true in an if when its length is not zero.

class Roster: # a template for objects def __init__(self, names): # runs when you create the object self.names = names # store this on the object def __len__(self): # define the function; it runs when you call it return len(self.names) # send this value back to the caller if Roster(["Asha"]): # run the indented lines only when this is true print("has students")
bool uses __len__ when __bool__ is missing. A length of 0 is treated as false.
Call Now 81900 98289