Python List Length

To know a Python list length, use the built-in len() function.

For instance:

nums = [1,2,3]
list_length = len(nums)




In this guide, you learn how to call the len() function on different objects in Python. You will also learn how to call len() on custom objects.

Using the len() Function in Python

Python comes with a built-in len() function. This is the most common way to calculate the length of a list.

Actually, you are not restricted to using len() function only on lists. You can use len() on:

Here are examples of each:

# Tuple
nums_tuple = (1, 2, 3, 4 ,5)
len(nums_tuple) # returns 5

# List
names_list = ["Alice", "Bob", "Charlie"]
len(names_list) # returns 3

# Dictionary
nums_dict = {"1": 1, "2": 2}
len(nums_dict) # returns 2

# Set
nums_set = {1, 2, 3, 4, 5, 6}
len(nums_set) # returns 6

# Range
num_range = range(100)
len(num_range) # returns 100

# Byte object
byte_obj = b'\x00\x04\x00'
len(byte_obj) # returns 3

A Naive Way to Calculate a Python List Length

Of course, you could calculate the list length using a for loop or a while loop:

nums = [1, 2, 3, 4, 5]

length = 0
for _ in nums:
    length += 1

print(f"The lenght of a lits is {length}")


The lenght of a lits is 5

Although this is impractical as you always have the len() function at your disposal.

Using len() Function on Your Class Objects

Let’s say you create a custom class called Fruit. Let’s also call the len() function on a Fruit object:

class Fruit:
    name = "Banana"
    length = 10

fruit = Fruit()

This results in an error that tells you the len() is a meaningless operation on a Fruit object:

TypeError: object of type 'Fruit' has no len()

This is no surprise because you do not really define the length of a Fruit, other than adding the length attribute to it.

In Python, calling the len() function on any object triggers a special method called __len__ under the hood.

What is cool is that Python allows you to override the __len__ function in your class. This allows you to call len() on your custom objects.

For example, let’s make it possible to call len() on a Fruit object so that it returns the length attribute of the fruit:

class Fruit:
    name = "Banana"
    length = 10

    def __len__(self):
        return self.length

# Example call
fruit = Fruit()



Under the hood calling len(fruit) is the same as calling fruit.__len__(), that you just implemented.





To get the length of a list in Python, use the built-in len() function.

For example:

len([1, 2, 3, 4]) # returns 4

You can use the len() function on lists, tuples, dictionaries, sets, ranges, and byte objects.

And if you implement __len__ in your own class, you can call len() on the class objects too.

Thanks for reading. I hope you find it useful.

Happy coding!

Further Reading

10+ Useful Python Tricks to Code Like a Pro


Python’s official Docs

Leave a Comment

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