(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:
1 | len(obj) -> length |
Parameter | Description |
---|---|
obj | obj can be a string, list, dictionary, tuple etc. |
Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 | >>> >>> len([1, 2, 3, 4, 5]) # length of list 5 >>> >>> len({"spande", "club", "diamond", "heart"}) # length of set 4 >>> >>> len(("alpha", "beta", "gamma")) # length of tuple 3 >>> >>> len({ "mango": 10, "apple": 40, "plum": 16 }) # length of dictionary 3 >>> |
Ironically, the len() function doesn’t work with a generator. Trying to call len() on a generator object will result in TypeError exception.
1 2 3 4 5 6 7 8 9 10 11 12 | >>> >>> def gen_func(): ... for i in range(5): ... yield i ... >>> >>> >>> len(gen_func()) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: object of type 'generator' has no len() >>> |
len() with User defined objects
To use len() on user-defined objects you will have to implement the __len__() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | >>> >>> class Stack: ... ... def __init__(self): ... self._stack = [] ... ... def push(self, item): ... self._stack.append(item) ... ... def pop(self): ... self._stack.pop() ... ... def __len__(self): ... return len(self._stack) ... >>> >>> s = Stack() >>> >>> len(s) 0 >>> >>> s.push(2) >>> s.push(5) >>> s.push(9) >>> s.push(12) >>> >>> len(s) 4 >>> |
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!