Python len() Function



The Python len() function is a built-in function that is used to determine the length of an object. Here, the object could be a string, a list, a dictionary, or any other iterable.

Please note that the len() only works on objects that are considered to be a collection. If we pass an integer or a float to this function, the interpreter will throw TypeError.

In the next few sections, we will learn this function in more detail.

Syntax

Following is the syntax of the Python len() function −

len(object)

Parameters

The Python len() function accepts a single parameter −

  • object − It represents an object such as a list, string, or dictionary.

Return Value

The Python len() function returns the length of specified object.

Examples

In this section, we will see some examples of len() function −

Example 1

If we pass a string to the len() function, it will retrieve the number of characters in the given string including punctuation, space, and all types of special characters. In the code below, we are defining a string and trying to find its length.

definedStr = "Welcome to Tutorials Point"
lengthOfStr = len(definedStr)
print("The length of the given string is:", lengthOfStr)

Following is an output of the above code −

The length of the given string is: 26

Example 2

Passing a list to the len() function returns the number of items available in that list. The code below demonstrates how to get a total number of elements from the specified list using len() function.

definedList = ["Simply", "Easy", "Learning", "Tutorials", "Point"]
lengthOfList = len(definedList)
print("The length of the given List is:", lengthOfList)

Output of the above code is as follows −

The length of the given List is: 5

Example 3

Since a dictionary is also a type of collection, it is supported by the len() function. In the following code, we are finding the length of a dictionary.

definedDict = {"OrgName":"Tutorialspoint", "Location":"Hyderabad"}
lengthOfDict = len(definedDict)
print("The length of the given dictionary is:", lengthOfDict)

Following is the output of the above Python code −

The length of the given dictionary is: 2
python_built_in_functions.htm
Advertisements