Python len()

The len() function returns the number of items (length) in an object.

Example


len() Syntax

The syntax of len() is:

len(s)

len() Parameters

The len() function takes a single argument s, which can be

  • sequence - string, bytes, tuple, list, range OR,
  • collection - dictionary, set, frozen set

len() Return Value

len() function returns the number of items of an object.

Failing to pass an argument or passing an invalid argument will raise a TypeError exception.


Example 1: How len() works with tuples, lists and range?

Output

[] length is 0
[1, 2, 3] length is 3
(1, 2, 3) length is 3
Length of range(1, 10) is 9

Visit these pages to learn more about:


Example 2: How len() works with strings and bytes?

Output

Length of  is 0
Length of Python is 6
Length of b'Python' is 6
Length of b'\x01\x02\x03' is 3

Visit these pages to learn more about:


Example 3: How len() works with dictionaries and sets?

Output

{1, 2, 3} length is 3
set() length is 0
{1: 'one', 2: 'two'} length is 2
{} length is 0
frozenset({1, 2}) length is 2

Visit these pages to learn more about:


Internally, len() calls the object's __len__ method. You can think of len() as:

def len(s):
    return s.__len__()

So, you can assign custom length to the object (if necessary)


Example 4: How len() works for custom objects?

Output

0
6