Course
The len()
function is one of the first tools Python programmers rely on to inspect data. You’re sure to have encountered len()
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:
len(object)
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:
word = "Josef"
print(len(word))
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:
numbers = [10, 20, 30, 40, 50]
print(len(numbers))
Here, you'll see 5
as 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:
dimensions = (1920, 1080)
print(len(dimensions))
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:
person = {"name": "Alice", "age": 30, "city": "Paris"}
print(len(person))
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:
colors = {"red", "green", "blue", "red"}
print(len(colors))
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:
class Box:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
my_box = Box(["apple", "banana", "orange"])
print(len(my_box))
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:
num = 42
print(len(num))
This triggers the following error:
TypeError: object of type 'int' has no len()
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 in range(len(fruits)):
print(f"Index {i}: {fruits[i]}")
This prints each fruit alongside its index, giving you both order and context.
Index 0: apple
Index 1: banana
Index 2: cherry
Checking for empty containers
Frequently, you'll want to know if a container—like a list or dictionary—is empty before proceeding:
cart = []
if len(cart) == 0:
print("Your shopping cart is empty.")
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:
username = "superlongusername"
if len(username) > 10:
username = username[:10]
print(username)
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 = 123
try:
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.
Here’s a quick recap:
class Team:
def __init__(self, players):
self.players = players
def __len__(self):
return len(self.players)
my_team = Team(["Alice", "Bob", "Cathy"])
print(len(my_team))
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.

I'm a data science writer and editor with contributions to research articles in scientific journals. I'm especially interested in linear algebra, statistics, R, and the like. I also play a fair amount of chess!