Python built-in functions
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
The simplest example is the len()
function, which counts the number of items in some kind of container object, such as a dictionary or list. You've seen it before, demonstrated as follows::
>>> len([1,2,3,4])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__...