Contents
Python – len()
Python len() built-in function returns an integer representing the number of items in the given iterable.
In this tutorial, you will learn the syntax of len() function, and then its usage with the help of example programs.
Syntax of len()
The syntax of len() function is
len(object)
where
Parameter | Description |
---|---|
object | An object of type string, bytes, list, range, dictionary, set, or frozen set. |
The len() function returns an integer value.
Examples
1. Length of a string
In this example, we will pass a Python String to len() function. len(str) function returns the length of this string.
Output
12
2. Length of bytes object
In this example, we will pass a bytes object to len() function. len(bytes) function returns the number of bytes in the given bytes object.
Output
2
3. Length of a list
In this example, we will pass a list to len() function. len(list) function returns the number of elements present in the list.
Output
3
4. Length of a range
In this example, we will pass a range object to len() function. len(range) function returns the number of sequence of numbers in the range.
Output
8
5. Length of a dictionary
In this example, we will pass a dictionary to len() function. len(dict) function returns the number of key:value pairs in this dictionary.
Output
3
6. Length of a set
In this example, we will pass a set to len() function. len() function returns the number of elements in this set.
Output
4
7. Length of a frozenset
In this example, we will pass a string to len() function. len(frozenset) function returns the number of elements present in the frozen set.
Output
2
Summary
In this tutorial of Python Examples, we learned how to use len() function to find the number of items in a given collection or sequence.