Python len() function


(Sponsors) Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!


The len() function counts the number of items in an object.

Its syntax is as follows:

ParameterDescription
obj obj can be a string, list, dictionary, tuple etc.

Here is an example:

Ironically, the len() function doesn’t work with a generator. Trying to call len() on a generator object will result in TypeError exception.

len() with User defined objects

To use len() on user-defined objects you will have to implement the __len__()  method.

 


Other Tutorials (Sponsors)

This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!


Leave a Reply

Your email address will not be published. Required fields are marked *