len()

len(s)
Returns: int · Updated March 13, 2026 · Built-in Functions
built-in length size count

The len() function returns the number of items in an object. The argument can be a sequence (string, bytes, tuple, list, range) or a collection (dict, set, frozenset).

Syntax

len(s)

Parameters

ParameterTypeDescription
ssequence or collectionThe object whose length is returned

Examples

Strings

len("hello")
# 5

len("")
# 0

len("café")
# 4  (characters, not bytes)

Lists and tuples

len([1, 2, 3])
# 3

len(())
# 0

Dictionaries and sets

len({"a": 1, "b": 2})
# 2

len({1, 2, 3, 3})
# 3  (duplicates removed in sets)

Ranges

len(range(10))
# 10

len(range(2, 10, 3))
# 3  (values: 2, 5, 8)

Custom Objects

Implement __len__ to make your own objects work with len():

class Playlist:
    def __init__(self, songs: list[str]):
        self.songs = songs

    def __len__(self) -> int:
        return len(self.songs)

playlist = Playlist(["Song A", "Song B", "Song C"])
print(len(playlist))
# 3

Common Patterns

Checking if a container is empty

# Preferred — truthy/falsy check
if not items:
    print("empty")

# Also works, but less idiomatic
if len(items) == 0:
    print("empty")

Errors

len() raises TypeError if the argument has no length:

len(42)
# TypeError: object of type 'int' has no len()

len(None)
# TypeError: object of type 'NoneType' has no len()

See Also