len() Built-in Function
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.
Python Program
string = 'hello world!'
n = len(string)
print(n)
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.
Python Program
bytes1 = b'\x00\x10'
n = len(bytes1)
print(n)
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.
Python Program
myList = [25, 74, 'hello']
n = len(myList)
print(n)
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.
Python Program
myRange = range(0, 8)
n = len(myRange)
print(n)
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.
Python Program
myDict = {'a':12, 'b':45, 'c':98}
n = len(myDict)
print(n)
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.
Python Program
mySet = {24, 85, 73, 66}
n = len(mySet)
print(n)
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.
Python Program
vowels = frozenset(('a', 'e', 'i', 'o', 'u'))
n = len(vowels)
print(n)
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.