In Python, the len() function is used to return the length (number of elements) of an object. This object can be a sequence type (such as strings, lists, tuples, byte sequences, etc.) or a mapping type (such as dictionaries).
Function Syntax
len(object)
Parameters:
object: The object whose length is to be calculated.
Calls the object's __len__() method to return the object's length or number of elements.
len() Function Examples
# Calculate length of string
string = "Hello, World!"
print(len(string)) # Output: 13
# Calculate length of list
my_list = [1, 2, 3, 4, 5]
print(len(my_list)) # Output: 5
# Calculate length of tuple
my_tuple = (1, 2, 3)
print(len(my_tuple)) # Output: 3
# Calculate length of dictionary (returns number of key-value pairs)
my_dict = {"a": 1, "b": 2, "c": 3}
print(len(my_dict)) # Output: 3
__len__() Method
Only objects that implement the __len__() method can use the len() function to calculate length. If an object doesn't implement __len__(), calling the len() function will raise a TypeError exception.
class A:
def __len__(self):
return 666
class B:
pass
a = A()
b = B()
print(len(a)) # Output: 666
print(len(b)) # TypeError: object of type 'B' has no len()