Python built-in Method - len()

www.igi‮oc.aeditf‬m

The len() function is a built-in method in Python that returns the number of items in an object. The object can be a string, list, tuple, dictionary, or any other collection.

The syntax for len() is simple:

len(object)

Here, object can be any collection or sequence of elements, and len() will return the number of items in that collection.

For example:

my_list = [1, 2, 3, 4, 5]
my_dict = {'a': 1, 'b': 2, 'c': 3}

print(len(my_list))    # 5
print(len(my_dict))    # 3

In the example above, we use the len() function to determine the length of a list my_list and a dictionary my_dict.

The len() function is useful when you need to know the size of an object, especially when working with large collections of data. It is often used in conjunction with loops to iterate over the elements of a collection.

Note that not all objects in Python have a length. For example, an integer or a floating-point number does not have a length, and attempting to use len() on such an object will raise a TypeError. Also note that len() can be overridden for custom objects by implementing the __len__() method.