Python len() function With Examples

Python len() function returns the length of the object. Generally, len() function is used with sequences (string, tuple) and collections (dict, set) to get the number of items.

Python len() function

Python len() function returns the length of the object. This function internally calls __len__() function of the object. So we can use len() function with any object that defines __len__() function.

Let’s look at some examples of using len() function with built-in sequences and collection objects.

Output:

Python len() Object

Let’s define a custom class with __len__() function and call len() function with it’s object as argument.

Output:

If we remove __len__() function from Employee object, we will get the following exception.

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

By admin

Leave a Reply

%d bloggers like this: