Python len()
Parameters:
len() accepts one of following as a parameter at a time-
- a sequence (string, bytes, list, tuples or range)
- collection(dictionary, sets or frozen set)
Return:
Returns a number
Example of len() with different python data structure:
l = [1, 2, 3, 4]print(f'Length of list is {len(l)}')t = (1, 2, 3)print(f'Length of tuple is {len(t)}')s = {1, 2, 3, 4, 5}print(f'Length of set is {len(s)}')d = {1: 'a', 2:'b', 3:'c'}print(f'Length of dictionary is {len(d)}')
Output:
Length of list is 4
Length of tuple is 3
Length of set is 5
Length of dictionary is 3
How to use len() with custom objects:
To use len(), __len__ functions is required to be defined in the custom class. Following is the example-
class Sample:
def __init__(self):
#do_someting
self.length = 2 def __len__(self):
return self.lengtha = Sample()
print(len(a))
Output:
2
Here, I hard coded the value of length for each Sample class object but it is not necessary value of length attribute could be changed and output will change accordingly.