Python len() function

Updated on Nov 10, 2019


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

Its syntax is as follows:

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
>>>

Try it out:

# length of list
print(len([1, 2, 3, 4, 5])) 

# length of set
print(len({"spande", "club", "diamond", "heart"}))
 
# length of tuple
print(len(("alpha", "beta", "gamma")))

# length of dictionary
print(len({ "mango": 10, "apple": 40, "plum": 16 }))

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()
>>>

Try it out:

def gen_func(): 
    for i in range(5):
        yield i
 
print(len(gen_func()))

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
>>>

Try it out:

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()
 
print(len(s))

s.push(2)
s.push(5)
s.push(9)
s.push(12)
 
print(len(s))

Other Tutorials (Sponsors)