Python len() function

Filed Under: Python

Python len() function returns the length of the object. Generally, len() function is used with sequences (string, tuple) and collections (dict, set) to get the number of items.

Python len() function

Python len() function returns the length of the object. This function internally calls __len__() function of the object. So we can use len() function with any object that defines __len__() function.

Let’s look at some examples of using len() function with built-in sequences and collection objects.


# len with sequence
print('string length =', len('abc'))  # string
print('tuple length =', len((1, 2, 3)))  # tuple
print('list length =', len([1, 2, 3, 4]))  # list
print('bytes length =', len(bytes('abc', 'utf-8')))  # bytes
print('range length =', len(range(10, 20, 2)))  # range

# len with collections
print('dict length =', len({"a": 1, "b": 2}))  # dict
print('set length =', len(set([1, 2, 3, 3])))  # set
print('frozenset length =', len(frozenset([1, 2, 2, 3])))  # frozenset

Output:


string length = 3
tuple length = 3
list length = 4
bytes length = 3
range length = 5
dict length = 2
set length = 3
frozenset length = 3

Python len() Object

Let’s define a custom class with __len__() function and call len() function with it’s object as argument.


class Employee:
    name = ''

    def __init__(self, n):
        self.name = n

    def __len__(self):
        return len(self.name)


e = Employee('Pankaj')

print('employee object length =', len(e))

Output:


employee object length = 6

If we remove __len__() function from Employee object, we will get the following exception.


TypeError: object of type 'Employee' has no len()
You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages