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 |
Return Values
The len()
function returns an int
representing the number of items.
How to Use len()
in Python
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)
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)
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)