Python len() Method

The len() function returns the length of the object. It returns total elements in an iterable or the number of chars in a string.




object: Required. An iterable or string.

Return Value:

Returns an integer value indicating total elements or chars.

The following example demonstrates the len() method.

Example: len()
print("Total Elements in list: ", len([1,2,3,4,5]))
print("Total Elements in tuple: ",len((1,2,3,4,5)))
print("Total Elements in set: ",len({1,2,3,4,5}))
print("Total Elements in dict: ",len({1:'one',2:'two',3:'three',4:'four',5:'five'}))
print("string length : ", len("Hello World"))
print("byte length: ",len(b"12345"))
print("range() length: ",len(range(0,10)))
Total Elements in list:  5
Total Elements in tuple:  5
Total Elements in set:  5
Total Elements in dict:  5
string length:  11
byte length:  5
range() length:  10

It throws the TypeError if the specified value is bool or int.

Example: len()
TypeError: object of type 'bool' has no len() 
TypeError: object of type 'int' has no len()
Want to check how much you know Python?