Python len()

Python len()

Python len() is a built in function that returns an integer representing the number of items in the object passed as argument to it.

Syntax of len()

The syntax of len() function is

len(object)

where the object could be of type string, bytes, list, range, dictionary, set or frozen set.

The function len() returns an integer.

Example 1: len(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)
Run

Output

12

Example 2: len(bytes)

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)
Run

Output

2

Example 3: len(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)
Run

Output

3

Example 4: len(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)
Run

Output

8

Example 5: len(dict)

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)
Run

Output

3

Example 6: len(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)
Run

Output

4

Example 7: len(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)
Run

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.