Python len()

Python len() builtin function takes an object: sequence or a collection, as argument and returns the number of items in the object.

In this tutorial, we will learn about the syntax of Python len() function, and learn how to use this function with the help of examples.

Syntax

The syntax of len() function is

</>
Copy
len(object)

where object may be a sequence or container.

A sequence could be a string, bytes, tuple, list, or range. A collection could be dictionary, set, or frozen set.

Returns

The function returns

Examples

1. Length of a string

In the following program, we will find the length of a String.

Python Program

</>
Copy
myString = 'abcdef'
length = len(myString)
print(f'Length of this string is {length}.')

Output

Length of this string is 6.

2. Length of a bytes object

In the following program, we will find the length of bytes object.

Python Program

</>
Copy
bytesObject = b'\x65\x66\x67\x00\x10\x00\x00\x00\x04\x00'
length = len(bytesObject)
print(f'Length of this bytes object is {length}.')

Output

Length of this bytes object is 10.

3. Length of a tuple

In the following program, we will find the length of tuple object.

Python Program

</>
Copy
tupleObject = ('A', 'B', 'C', 'D')
length = len(tupleObject)
print(f'Length of this tuple is {length}.')

Output

Length of this tuple is 4.

4. Length of a list

In the following program, we will find the length of list object.

Python Program

</>
Copy
myList = ['a', 'bc', 'd', 'ef']
length = len(myList)
print(f'Length of this list is {length}.')

Output

Length of this list is 4.

5. Length of a range object

In the following program, we will find the length of range object.

Python Program

</>
Copy
rangeObject = range(2, 9)
length = len(rangeObject)
print(f'Length of this range is {length}.')

Output

Length of this range is 7.

6. Length of a dictionary

In the following program, we will find the length of Dictionary object.

Python Program

</>
Copy
dictObject = {'a': 24, 'b': 78, 'c': 33}
length = len(dictObject)
print(f'Length of this dictionary is {length}.')

Output

Length of this dictionary is 3.

7. Length of a set

In the following program, we will find the length of Set object.

Python Program

</>
Copy
setObject = {'a', 'b', 'c'}
length = len(setObject)
print(f'Length of this set is {length}.')

Output

Length of this set is 3.

8. Length of a frozen set

In the following program, we will find the length of Frozen Set object.

Python Program

</>
Copy
frozensetObject = frozenset({'a', 'b', 'c', 'd'})
length = len(frozensetObject)
print(f'Length of this frozen set is {length}.')

Output

Length of this frozen set is 4.

Conclusion

In this Python Tutorial, we have learnt the syntax of Python len() builtin function, and also learned how to use this function, with the help of Python example programs.