Python len(): A Beginner’s Guide to Counting Elements in Python
Learn how to use the Python len() function to quickly find the size of strings, lists, dictionaries, and other data structures. Discover practical examples and common mistakes to avoid when working with len() in your own code.
In this article, I’ll show you how len() works in Python across all the common data types, and I’ll show you what to watch for when things go wrong.
What Does the Python len() Function Do?
You can use Python's built-in len() function whenever you need to check how many items something holds. I'm thinking about counting the number of elements in a list or counting the number of characters in a string. You can also use it to count the keys in a dictionary. There are all kinds of uses.
Just place whatever you want to measure (like the things I listed above) in place of object.
Using len() with Common Python Data Types
I listed some common use cases above, but they were all a little abstract. Let's work through common examples to make the value of using len() more obvious.
Counting characters in a string
Suppose you want to know the exact length of a piece of text, including every space and punctuation mark:
This returns 3, since "red" appears twice but counted once.
How len() Works Under the Hood
You might be wondering, like I did, how len() actually determines size.
Underneath, when you call len() on an object, Python looks for that object’s __len__ method. Built-in types like lists, strings, and dictionaries all have this method.
Knowing this tells us that, if we create your own class and want len() to work with it, we have to define a __len__ method ourself:
classBox:def__init__(self, items):
self.items = items
def__len__(self):returnlen(self.items)
my_box = Box(["apple","banana","orange"])print(len(my_box))Funcționează cu
Here, len() returns 3, because the box holds three items. Just like we did with lists and strings, len() adapts as long as the object provides a __len__ method.
What Happens When len() Doesn't Work?
Of course, not everything in Python has a length. If you try using len() on something that doesn't support it (I'll show you in a second with an int data type) Python will let you know with a TypeError. This is a common thing people run into, especially if they are working with mixed data types. For instance:
Whenever you see this, double-check that the object you're measuring is actually a container or sequence (string, list, or dictionary) and that it's not a single value such as an integer or a float.
Some Handy len() Use Cases
Let's not try to elevate the examples to resemble things that are more like real-world programming situations.
Looping with a range
When you need to loop through a list using its indices, len() helps you set up the right range for your loop:
fruits =["apple","banana","cherry"]for i inrange(len(fruits)):print(f"Index {i}: {fruits[i]}")
Here, any username longer than 10 characters is trimmed down.
Common Mistakes with len()
len() can trip you up, even if you have some experience with Python:
Trying to use len() on integers or floats: Numbers aren’t collections, so they don’t have a length.
Forgetting that len() counts items, not values: In a dictionary, len counts keys—even if several keys point to the same value.
Assuming len() works on everything: Custom classes need a __len__ method; otherwise, len() won’t know what to do.
Do try to remember these rules to save some time debugging.
Error Handling with len()
Given that len() can raise a TypeError if misused, it’s wise to prepare your code for this possibility, especially when working with unpredictable data. A try-except block is a simple way to handle such errors gracefully:
data =123try:print(len(data))except TypeError:print("Object has no length.")
Instead of crashing, your program now prints a friendly message. Our Object-Oriented Programming in Python course is a great resource to get good at this kind of thing.
Using len() with Custom Classes
Let’s circle back to custom classes. A custom class is any class you define yourself using the class keyword—like when you’re modeling something specific to your program, such as a Team, Box, or Library. Earlier, you saw that len() works on built-in types like lists and dictionaries because they implement a special method called __len__(). The same applies to your own classes. If you want len() to work on them, you need to define __len__() yourself.
I'm not trying to bog you down with a technical detail. I think it's worth mentioned this because it's important when you're building custom data containers that should behave like native Python collections. By supporting len(), your objects can interact more naturally with the rest of the Python ecosystem, including other functions and libraries.
Again, len() returns 3, which is the right answer since this is the number of players in your team.
Conclusion
The next time you need to count, measure, or verify the size of something in Python, remember that len() is one great option.
But now that we've gotten to the end, I want to mention another important thing. We focused on one function, but there are almost always many different ways to accomplish something in Python. We have an article that even shows many different ways to find the length of a list, of which the len() function is just one option: Python List Size: 8 Different Methods for Finding the Length of a List in Python.
Keep practicing new methods. It's a surefire way to make you into a stronger programmer. And remember to enroll in our Python Programming skill track, which will teach you how to optimize code, write functions and tests, and so much more.
Autor
Josef Waples
I'm a data science editor with contributions to research articles in scientific journals. I'm especially interested in linear algebra, statistics, R, and the like.
There are several ways to find the size of a DataFrame in Python to fit different coding needs. Check out this tutorial for a quick primer on finding the size of a DataFrame. This tutorial presents several ways to check DataFrame size, so you’re sure to find a way that fits your needs.
The
len()function is one of the first tools Python programmers rely on to inspect data. You’re sure to have encounteredlen()if you're working through our Introduction to Python for Developers course or our Python Programming Fundamentals skill track.In this article, I’ll show you how
len()works in Python across all the common data types, and I’ll show you what to watch for when things go wrong.What Does the Python len() Function Do?
You can use Python's built-in
len()function whenever you need to check how many items something holds. I'm thinking about counting the number of elements in a list or counting the number of characters in a string. You can also use it to count the keys in a dictionary. There are all kinds of uses.Here’s how you use it in its most basic form:
Just place whatever you want to measure (like the things I listed above) in place of
object.Using len() with Common Python Data Types
I listed some common use cases above, but they were all a little abstract. Let's work through common examples to make the value of using
len()more obvious.Counting characters in a string
Suppose you want to know the exact length of a piece of text, including every space and punctuation mark:
This prints
5, since the word"Josef"(with an "f") consists of five characters.Checking the number of items in a list
If you want to find out how many items a list contains, use this:
Here, you'll see
5as the output.Getting the size of a tuple
Tuples, much like lists, group items together but are immutable, meaning they can't be changed after creating them.
len()works here, too:This produces
2, since the tuple stores two elements.Counting keys in a dictionary
Python dictionaries are all about key-value pairs. When you use
len()on a dictionary, it counts just the keys:So you get
3(one for each key).Checking unique elements in a set
Sets are handy when you want to store only unique items.
len()will tell you:This returns
3, since"red"appears twice but counted once.How len() Works Under the Hood
You might be wondering, like I did, how
len()actually determines size.Underneath, when you call
len()on an object, Python looks for that object’s__len__method. Built-in types like lists, strings, and dictionaries all have this method.Knowing this tells us that, if we create your own class and want
len()to work with it, we have to define a__len__method ourself:Here,
len()returns3, because the box holds three items. Just like we did with lists and strings,len()adapts as long as the object provides a__len__method.What Happens When len() Doesn't Work?
Of course, not everything in Python has a length. If you try using
len()on something that doesn't support it (I'll show you in a second with anintdata type) Python will let you know with aTypeError. This is a common thing people run into, especially if they are working with mixed data types. For instance:This triggers the following error:
Whenever you see this, double-check that the object you're measuring is actually a container or sequence (string, list, or dictionary) and that it's not a single value such as an integer or a float.
Some Handy len() Use Cases
Let's not try to elevate the examples to resemble things that are more like real-world programming situations.
Looping with a range
When you need to loop through a list using its indices,
len()helps you set up the right range for your loop:This prints each fruit alongside its index, giving you both order and context.
Checking for empty containers
Frequently, you'll want to know if a container—like a list or dictionary—is empty before proceeding:
This pattern helps you avoid errors or unnecessary processing when there's nothing to work with.
Truncating long strings
If you're dealing with user input or displaying labels, you might want to limit string length.
len()helps you enforce those boundaries:Here, any username longer than 10 characters is trimmed down.
Common Mistakes with len()
len()can trip you up, even if you have some experience with Python:Trying to use len() on integers or floats: Numbers aren’t collections, so they don’t have a length.
Forgetting that len() counts items, not values: In a dictionary, len counts keys—even if several keys point to the same value.
Assuming len() works on everything: Custom classes need a
__len__method; otherwise,len()won’t know what to do.Do try to remember these rules to save some time debugging.
Error Handling with len()
Given that
len()can raise aTypeErrorif misused, it’s wise to prepare your code for this possibility, especially when working with unpredictable data. A try-except block is a simple way to handle such errors gracefully:Instead of crashing, your program now prints a friendly message. Our Object-Oriented Programming in Python course is a great resource to get good at this kind of thing.
Using len() with Custom Classes
Let’s circle back to custom classes. A custom class is any class you define yourself using the
classkeyword—like when you’re modeling something specific to your program, such as aTeam,Box, orLibrary. Earlier, you saw thatlen()works on built-in types like lists and dictionaries because they implement a special method called__len__(). The same applies to your own classes. If you wantlen()to work on them, you need to define__len__()yourself.I'm not trying to bog you down with a technical detail. I think it's worth mentioned this because it's important when you're building custom data containers that should behave like native Python collections. By supporting
len(), your objects can interact more naturally with the rest of the Python ecosystem, including other functions and libraries.Here’s a quick recap:
Again,
len()returns3, which is the right answer since this is the number of players in your team.Conclusion
The next time you need to count, measure, or verify the size of something in Python, remember that
len()is one great option.But now that we've gotten to the end, I want to mention another important thing. We focused on one function, but there are almost always many different ways to accomplish something in Python. We have an article that even shows many different ways to find the length of a list, of which the
len()function is just one option: Python List Size: 8 Different Methods for Finding the Length of a List in Python.Keep practicing new methods. It's a surefire way to make you into a stronger programmer. And remember to enroll in our Python Programming skill track, which will teach you how to optimize code, write functions and tests, and so much more.