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)

print(list_length)

Output:

3

Did you know you can call len() on your own class objects in Python? To learn how to do this and more, please read along.

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:

  • Lists
  • Tuples
  • Sets
  • Dictionaries
  • Ranges
  • Byte objects

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}")

Output:

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. Calling len() on a Fruit object seems pretty dumb, right?

class Fruit:
    name = "Banana"
    length = 10

fruit = Fruit()
len(fruit)

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

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

But to your surprise, you can make it work.

Python lets you implement a special method called __len__ in your class. This allows you to call len() on an object that represents the class.

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

class Fruit:
    name = "Banana"
    length = 10

    def __len__(self):
        return self.length

fruit = Fruit()
print(len(fruit))

Output:

10

Now calling len() on your custom type works.

Conclusion

To get the list length in Python, use the built-in len() function by passing a list into it.

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

Resources

Python’s official Docs

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest

Leave a Comment

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