Python len() Function Tutorial

In this section, we will learn what the len() function is and how to use it in Python.

len() Function in Python

The Python len() function is used to get the length of an object. For iterable objects, this function will return the number of items in there.

This function works easily with any iterable object (Like String, List, Dictionary, Set etc.) but if the target object is a custom made one, then we should already implemented the __len__ method within that object and the len() function will return whatever is set as the return value for the __len__ method! Otherwise, a type of error will return if the object is not iterable, or it’s a custom object with no __len__ method.

Python len() Function Syntax:

len(object)

Python len() Function Parameters

The function takes one argument and that is a reference to the object that we want to get its length.

Python len() Function Return Value

The return value of this method is an integer number which is equal to the length of items in the target object.

Example: python length of list

list1 = [1,2,3,4,5,6,7,8,9,0]

print(len(list1))

Output:

10

Example: length of string python

string = "This is a simple sentence"

print(len(string))

Output:

25
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies