Python len()
is a built-in function that returns the length(number of items ) of an object.
pyy
len(s)
len()
function takes only one parameter as argument.
The parameter can be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).
A TypeError
is raised if no argument is supplied or an invalid argument is supplied to the function len()
.
Many people get confused with the difference between __len__()
and len()
method.
Well, len(s)
is a built-in Python method which returns the length of an object. Now __len__()
is a special method that is internally called by len(s)
method to return the length of an object.
So, when we call len(s)
method, s.__len__()
is what actually happening behind the scenes to calculate the length.
The Python len()
function can be interpreted as:
def len(s):
return s.__len__()
>>> list1 = []
>>> len(list1)
0
>>> list2 = [1,2,3]
>>> len(list2)
3
>>> tuple1 = ()
>>> len(tuple1)
0
>>> tuple2 = (1,2,3)
>>> len(tuple2)
3
>>> str1 = ''
>>> len(str1)
0
>>> str2 = 'Python'
>>> len(str2)
6
>>> set1 = {}
>>> len(set1)
0
>>> set2= {1,2,3}
>>> len(set2)
3
>>> class Example:
def __len__(self):
return 6
>>> obj = Example()
>>> obj.__len__()
6
>>> len(obj)
6