How to use len() in Python

Learn different ways to use Python's len() function. Get tips, see real-world applications, and learn how to debug common errors.

How to use len() in Python
Published on: 
Fri
Feb 13, 2026
Updated on: 
Mon
Apr 13, 2026
The Replit Team

Python's built-in len() function is a fundamental tool for developers. It provides a simple way to count the number of items in data types like strings, lists, and dictionaries.

In this guide, you'll explore core techniques and practical tips for len(). You will also find real-world applications and advice to fix common errors, so you can use the function effectively.

Basic usage of len()

text = "Hello, world!"
numbers = [1, 2, 3, 4, 5]
user_info = {"name": "Alice", "age": 30}
print(f"Length of string: {len(text)}")
print(f"Length of list: {len(numbers)}")
print(f"Length of dictionary: {len(user_info)}")--OUTPUT--Length of string: 13
Length of list: 5
Length of dictionary: 2

The example demonstrates how len() adapts its counting method based on the data type you provide. It's not just a simple item counter; its behavior is context-specific, which is why it's so versatile.

  • String: For the text variable, it counts every character, including spaces and punctuation.
  • List: With the numbers list, it returns the total count of elements inside it.
  • Dictionary: For the user_info dictionary, it counts the number of key-value pairs, not the total number of keys and values combined.

Common uses of len() with different data types

The versatility of len() extends beyond simple counting, making it a cornerstone for text processing, collection management, and handling dictionaries or sets.

Using len() with strings for text processing

message = "Python programming"
if len(message) > 10:
print("That's a long message!")
empty_string = ""
is_empty = len(empty_string) == 0
print(f"Is the string empty? {is_empty}")--OUTPUT--That's a long message!
Is the string empty? True

When working with strings, len() is perfect for validation and control flow. You can use it inside an if statement to check if a string's length meets a certain condition, like ensuring a username isn't too long. This is one of many approaches for counting characters in Python.

  • The first part of the code checks if the message variable has more than 10 characters.
  • The second part confirms if a string is empty by checking if its length is exactly 0, a common and reliable technique.

Using len() with lists for collection management

fruits = ["apple", "banana", "cherry"]
print(f"You have {len(fruits)} fruits in your basket")

# Check if list has at least 2 elements
if len(fruits) >= 2:
print(f"First two fruits: {fruits[0]} and {fruits[1]}")--OUTPUT--You have 3 fruits in your basket
First two fruits: apple and banana

For lists, len() is essential for managing collections. It helps you keep track of the number of items and prevents errors when accessing elements by their index. This technique also applies to finding the length of arrays.

  • The code first prints the total count of items in the fruits list, which is a straightforward way to get a summary.
  • More importantly, it uses len() with the >= operator as a guardrail. This check ensures the list contains at least two elements before you try to access them—a great practice to avoid an IndexError.

Using len() with dictionaries and sets

student = {"name": "John", "age": 21, "courses": ["Math", "Physics"]}
print(f"Student record has {len(student)} attributes")

unique_visitors = {"user123", "user456", "user789", "user123"}
print(f"There were {len(unique_visitors)} unique visitors")--OUTPUT--Student record has 3 attributes
There were 3 unique visitors

The len() function is just as useful for dictionaries and sets, offering a quick way to gauge their size without manual counting.

  • With the student dictionary, it counts the top-level key-value pairs. Notice it returns 3, representing the main attributes (name, age, and courses), not the items inside the nested list.
  • For the unique_visitors set, len() returns the number of unique items. Since sets automatically discard duplicates, it correctly reports 3 unique visitors despite "user123" appearing twice.

Advanced applications of len()

Moving beyond the basics, len() also unlocks advanced patterns for defining custom object lengths, creating concise list comprehensions, and working efficiently with iterables.

Implementing __len__() in custom classes

class Playlist:
def __init__(self, songs):
self.songs = songs

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

my_playlist = Playlist(["Song1", "Song2", "Song3"])
print(f"Playlist contains {len(my_playlist)} songs")--OUTPUT--Playlist contains 3 songs

By implementing the special __len__() method, you can teach Python's built-in len() function how to measure your custom objects. This lets you define what "length" means for creating custom classes in Python, making your code more intuitive.

  • In the Playlist example, the __len__() method simply returns the length of the internal songs list.
  • When Python sees len(my_playlist), it automatically calls the my_playlist.__len__() method behind the scenes.
  • This practice makes your custom objects feel more like native Python data structures.

Using len() in list comprehensions and conditionals

words = ["apple", "banana", "kiwi", "strawberry", "orange"]
short_words = [word for word in words if len(word) < 6]
word_lengths = [len(word) for word in words]
print(f"Short words: {short_words}")
print(f"Word lengths: {word_lengths}")--OUTPUT--Short words: ['apple', 'kiwi']
Word lengths: [5, 6, 4, 10, 6]

List comprehensions offer a concise way to create new lists, and len() fits right in. You can use it to filter items based on their length or to transform items into their lengths, all in a single line.

  • The short_words list is created by filtering words. The condition if len(word) < 6 keeps only the words with fewer than six characters.
  • The word_lengths list is generated by applying len() to every word, efficiently transforming the original list of strings into a new list of their corresponding lengths.

Using len() with iterables and generators

from functools import reduce

# Check if all strings in a tuple have the same length
colors = ("red", "blue", "gold")
all_same_length = reduce(lambda x, y: x and y,
[len(color) == len(colors[0]) for color in colors])
print(f"All strings have the same length: {all_same_length}")--OUTPUT--All strings have the same length: False

The len() function is powerful when combined with other tools to process iterables like tuples. In this example, it's used inside a list comprehension to check if every string in the colors tuple has the same length as the first one. This creates a temporary list of boolean values—True or False—for each comparison.

  • The list comprehension, [len(color) == len(colors[0]) for color in colors], iterates through the tuple and compares the length of each color to the length of the first element.
  • The reduce() function then processes this list of booleans. It uses a logical and to confirm if all values are True, giving you a single result that tells you if all strings share the same length.

Move faster with Replit

Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly.

Instead of piecing together techniques, you can describe the app you want to build and Agent 4 will take it from a description to a working product:

  • A username validator that uses len() to enforce character limits for a sign-up form.
  • A simple inventory tracker that counts items in a list and alerts you when the stock count drops below a certain level.
  • A text analysis tool that calculates the average word length from a block of text by using len() on each word.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

While len() is straightforward, you might run into a few common pitfalls, especially with certain data types and complex structures.

The most frequent issue is a TypeError, which occurs if you pass an object that has no defined length. Data types like integers or floats don't support len() because they aren't collections of items. To prevent this, ensure the object is a sequence like a string, list, or dictionary before calling the function.

Generators also present a unique challenge. Because they produce items on the fly instead of storing them all at once, they don't have a length, and using len() on them will cause an error. If you need the total count, you can convert the generator to a list—for example, len(list(my_generator))—but be aware this consumes the generator and loads all its items into memory.

When dealing with nested structures, remember that len() only counts the top-level elements. It won't automatically tally all the items inside the nested collections.

  • For a list like [[1, 2], [3, 4]], len() returns 2, not 4, because it counts the two inner lists.
  • To get the total number of individual items, you would need to loop through the structure and sum the lengths of each inner list.

Handling TypeError when using len() with non-iterable objects

You'll get a TypeError if you use len() on an object without a defined length, such as an integer or a float. These data types aren't collections, so Python can't count their items. The code below shows this error in action.

number = 42
length = len(number)
print(f"Length: {length}")

The code fails because len() can't measure the integer assigned to number. It's like asking for the length of a single, indivisible value. The following example demonstrates a safe way to handle this situation before calling the function.

number = 42
if hasattr(number, "__len__"):
print(f"Length: {len(number)}")
else:
print(f"Cannot get length of {type(number).__name__}")

The safe approach is to check if an object can be measured before calling len(). You can do this with the hasattr() function, which confirms if an object has a __len__ method. This check lets you avoid a TypeError by handling non-iterable objects gracefully.

  • If hasattr(your_variable, "__len__") returns True, it's safe to use len().
  • If it's False, you can run alternative code instead of crashing.

This is a great defensive technique when your function receives data of an unknown type, and it complements other strategies for handling multiple exceptions in Python.

Using len() with generator objects

Generators are memory-efficient because they produce values on demand instead of storing them all at once. This 'lazy' evaluation means they don't have a predefined length, so you can't check their size directly with len().

Attempting to do so will raise a TypeError, as the following code demonstrates.

numbers_generator = (x for x in range(10))
print(f"Generator length: {len(numbers_generator)}")

The numbers_generator object only creates values as they're needed, so it has no fixed size for len() to measure. The code below demonstrates the correct way to get the total count from a generator.

numbers_generator = (x for x in range(10))
numbers_list = list(numbers_generator)
print(f"Generator length: {len(numbers_list)}")

To find a generator's length, you must first convert it into a list, like with list(numbers_generator). After the conversion, you can safely call len() on the new list to get the total item count.

  • Keep in mind this approach consumes the generator and loads all its items into memory, which can be costly for large datasets.

Counting elements in nested structures

A common point of confusion arises when using len() with nested structures. The function doesn't count the individual items inside, only the top-level containers. This can lead to unexpected results, as the following code demonstrates.

nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
print(f"Total number of elements: {len(nested_list)}")

The code returns 3 because len() counts the three inner lists, not the nine numbers they contain. To get the total count of every individual item, you need a different approach. The example below shows how to do it correctly.

nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
total_elements = sum(len(sublist) for sublist in nested_list)
print(f"Total number of elements: {total_elements}")

The correct approach uses a generator expression inside the sum() function. This combination iterates through the main list, gets the length of each inner list, and adds those lengths together for a final count.

  • The expression (len(sublist) for sublist in nested_list) calculates the size of each sublist.
  • sum() then totals these individual sizes.

This is a powerful pattern for handling data from sources like APIs or files, where information is often organized in nested collections.

Real-world applications

Beyond handling errors and advanced patterns, len() is crucial for practical tasks like text analysis and input validation.

Using len() for text analysis and content metrics

You can use len() to quickly break down a block of text into useful metrics for text analysis, such as the total number of lines, words, and even the average length of each word.

# Analyze text content for metrics
article = "Python is a versatile language.\nIt's used for web development, data analysis, and AI."
lines = article.split('\n')
words = article.split()
avg_word_length = sum(len(word) for word in words) / len(words)
print(f"Lines: {len(lines)}, Words: {len(words)}")
print(f"Average word length: {avg_word_length:.1f} characters")

This example showcases how len() works with string manipulation. The code uses the split() method to break the article string into separate lists of lines and words. It then calculates the average word length in a single, efficient line, building on techniques used for counting words in Python.

  • A generator expression, (len(word) for word in words), produces the length of each word on the fly.
  • The sum() function adds all these lengths together.
  • This total is then divided by len(words) to get the final average.

Using len() for input validation in web applications

In web development, len() is a go-to function for validating user input, ensuring that fields like usernames and passwords meet specific length requirements.

def validate_user_input(username, password):
errors = []
if len(username) < 3:
errors.append("Username must be at least 3 characters")
if len(password) < 8:
errors.append("Password must be at least 8 characters")

return "Registration successful!" if len(errors) == 0 else errors

print(validate_user_input("jo", "pass123"))
print(validate_user_input("john_doe", "secure_password"))

This validate_user_input function shows a flexible way to handle form validation. Instead of stopping at the first mistake, it gathers all input failures into an errors list, which lets you provide comprehensive feedback to a user all at once. This approach works well in vibe coding sessions.

  • The function’s outcome depends on the final return statement, which uses a conditional expression.
  • It checks if len(errors) == 0. If the list is empty, it means no errors were found, and a success message is returned.
  • If the list contains items, the function returns the list itself, detailing exactly what went wrong.

Get started with Replit

Now, turn your knowledge of len() into a functional tool. Describe what you want to build to Replit Agent, like "a username validator that checks character length" or "a simple text analyzer that counts words."

Replit Agent will write the code, test for errors, and deploy your application for you. Start building with Replit.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.