Python len() Function Explained

The built-in len() function returns the size of an object.

Beginners often use len() to count:

  • characters in a string
  • items in a list or tuple
  • keys in a dictionary
  • unique items in a set

It is a simple but very useful function. You will use it often when checking if something is empty, validating input, or counting stored values safely.

Quick example

text = "hello"
items = [10, 20, 30]

print(len(text))   # 5
print(len(items))  # 3

Use len() to get the number of characters in a string or the number of items in a container like a list, tuple, set, or dictionary.

What len() does

len() returns the size of an object.

Here is what that means for common Python types:

  • For strings, it counts characters
  • For lists, tuples, and sets, it counts items
  • For dictionaries, it counts keys
  • It always returns an integer

Example:

name = "Sam"
numbers = [10, 20, 30, 40]
data = {"a": 1, "b": 2}
values = {5, 6, 7}

print(len(name))     # 3
print(len(numbers))  # 4
print(len(data))     # 2
print(len(values))   # 3

If you are still learning these data types, see Python strings explained, Python lists explained, and Python dictionaries explained.

Basic syntax

The syntax is:

len(object)

You pass one object inside the parentheses.

That object must be something that has a length, such as:

  • a string
  • a list
  • a tuple
  • a set
  • a dictionary

Example:

print(len("python"))      # 6
print(len([1, 2, 3]))     # 3
print(len((10, 20)))      # 2
print(len({"x": 1}))      # 1

Using len() with strings

When you use len() on a string, Python counts every character.

That includes:

  • letters
  • spaces
  • punctuation

Example:

text = "Hi there!"
print(len(text))  # 9

Why is the result 9?

  • H = 1
  • i = 1
  • space = 1
  • t h e r e ! = 6

Total: 9

An empty string has length 0:

empty_text = ""
print(len(empty_text))  # 0

This matters when checking user input:

user_name = "Alice"

if len(user_name) >= 3:
    print("Name is long enough")

Using len() with lists and tuples

For lists and tuples, len() counts how many elements are stored.

Example with a list:

colors = ["red", "green", "blue"]
print(len(colors))  # 3

Example with a tuple:

point = (10, 20)
print(len(point))  # 2

This is useful before indexing so you do not try to access an item that is not there:

items = ["apple", "banana"]

if len(items) > 1:
    print(items[1])  # banana

It is also common in loops and checks:

scores = [88, 91, 75]
print("Number of scores:", len(scores))

If you want a task-focused example, see how to get the length of a list in Python.

Using len() with dictionaries and sets

For dictionaries, len() counts keys.

student = {
    "name": "Mia",
    "age": 12,
    "grade": "A"
}

print(len(student))  # 3

Even though the dictionary has keys and values, len() returns the number of keys.

For sets, len() counts unique items:

numbers = {1, 2, 3, 3, 2}
print(len(numbers))  # 3

The repeated values are removed in a set, so only unique items are counted.

This is useful when checking if a collection is empty:

data = {}

if len(data) == 0:
    print("The dictionary is empty")

Common beginner use cases

Here are some practical ways beginners use len().

Check if a list is empty

items = []

if len(items) == 0:
    print("The list is empty")

Count letters in user input

word = input("Enter a word: ")
print("Number of characters:", len(word))

Validate minimum password length

password = "secret123"

if len(password) >= 8:
    print("Password length is valid")
else:
    print("Password is too short")

Check how many items were read

results = ["item1", "item2", "item3"]
print("Items found:", len(results))

These are the kinds of small checks that make programs safer and easier to debug.

Objects that can cause errors

len() does not work on every value.

These will raise a TypeError:

  • plain integers
  • floats
  • None

Example:

print(len(5))

This causes an error because the integer 5 does not have a length.

Another example:

print(len(3.14))

And with None:

value = None
print(len(value))

If your code fails because a value is missing, it may help to read TypeError: 'NoneType' object is not iterable.

How to avoid mistakes

Before using len(), make sure the value is a string or collection.

Helpful debugging steps:

value = None

print(value)
print(type(value))
print(isinstance(value, str))
print(isinstance(value, list))
print(isinstance(value, dict))

This helps you see what the variable actually contains.

You can also use a safe check:

value = "hello"

if value is not None:
    print(len(value))

If you are learning how to inspect values, see Python type() function explained.

Common mistakes

Here are some common beginner mistakes when using len():

  • Using len() on an integer like len(5)
  • Using len() on a float like len(3.14)
  • Using len() on None after a function returns nothing
  • Assuming len(dictionary) counts values instead of keys
  • Forgetting that spaces count in string length

Example of a dictionary misunderstanding:

person = {"name": "Ana", "age": 20}
print(len(person))  # 2

The result is 2 because there are two keys: "name" and "age".

Example showing that spaces count:

text = "a b"
print(len(text))  # 3

The space in the middle is counted as a character.

FAQ

What does len() return in Python?

It returns an integer that shows how many characters or items an object contains.

Does len() count spaces in a string?

Yes. Spaces are characters, so they are included.

What does len() return for a dictionary?

It returns the number of keys in the dictionary.

Can I use len() on a number?

No. Using len() on an int or float raises a TypeError.

How do I check if a list is empty?

You can use len(my_list) == 0.

Example:

my_list = []

if len(my_list) == 0:
    print("Empty list")

You should also learn that an empty list is treated as False in an if statement, but len() is often clearer for beginners.

See also