Python Built-in Functions

Learn how Python’s built-in functions leverage duck typing and facilitate common operations across various data types.

There are numerous functions in Python that perform a task or calculate a result on certain types of objects without being methods on the underlying class. They usually abstract common calculations that apply to multiple types of classes. This is duck typing at its best; these functions accept objects that have certain attributes or methods, and are able to perform generic operations using those methods. We’ve used many of the built-in functions already, but let’s quickly go through the important ones and pick up a few neat tricks along the way.

The len() function

One simple example of functions that are related to object methods is the len() function, which returns the number of items in some kind of container object, such as a dictionary or list. We’ve seen it before, demonstrated as follows:

Press + to interact
print(len([1, 2, 3, 4]))

You may wonder why these objects don’t have a length property instead of having to call a function on them. Technically, they do. Most objects that len() will apply to have a method called __len__() that returns the same value. So len(myobj) seems to call myobj.__len__().

Reasons to use the len() function

Here’re a few reasons why we should use the len() function in our program:

  • Why should we use the len() function instead of the __len__() method? Obviously, __len__() is a special double-underscore method, suggesting that we shouldn’t call it directly. There must be an explanation for this. The Python developers don’t make such design decisions lightly.

  • The main reason is efficiency. When we call the __len__() method of an object, the object has to look the method up in its namespace, and, if the special ...