Skip to main content

len()

The len() function in Python is a built-in function that returns the number of items in a container, such as a string, list, tuple, dictionary, etc. It calculates the length of the object and is commonly used to measure the size of data structures.

Parameter Values

Parameter Description
s

The s parameter is the sequence (string, bytes, tuple, list, or range) whose length is to be returned. It can also be a collection or an object that implements the __len__ method.

Return Values

The len() function returns an int representing the number of items.

How to Use len() in Python

Example 1:

The len() function returns the number of items in an object. For strings, it returns the number of characters in the string.

string = 'Hello World'
length = len(string)
print('Length of string:', length)
Example 2:

The len() function can also be used to determine the number of elements in a list.

my_list = [1, 2, 3, 4, 5]
list_length = len(my_list)
print('Length of list:', list_length)
Example 3:

The len() function works with other iterable objects like dictionaries, where it returns the number of key-value pairs in the dictionary.

my_dict = {'a': 1, 'b': 2, 'c': 3}
dict_length = len(my_dict)
print('Length of dictionary:', dict_length)