Python len() Function

Short answer
len(obj) returns the number of items in a container as an int: characters in a string, elements in a list or tuple, keys in a dictionary.

len() answers the question "how many?". You use it to check whether a list is empty, to validate the length of a password, or to find the last valid index in a loop. It works on any object that knows its own size, which includes all the built-in sequences and collections.

It does not work on numbers or on one-shot objects such as generators, because they have no stored length.

Quick facts
Syntaxlen(obj)
Parametersobj: a sequence (string, list, tuple, range, bytes) or a collection (dict, set)
ReturnsAn int that is 0 or greater
Time complexityO(1): the size is stored, not counted on each call

What len() counts for each data type

TypeWhat is countedExampleResult
strCharacters (Unicode code points)len('Python')6
listElementslen([4, 8, 15])3
tupleElementslen((1, 2))2
dictKeys (one per key-value pair)len({'a': 1, 'b': 2})2
setUnique elementslen({1, 1, 2})2
rangeNumbers producedlen(range(0, 10, 2))5

Using len() to check for empty data and to index safely

A collection is empty when len() is 0, but in an if you can usually just write if cart: because an empty collection is falsy (see truthy and falsy values). Use len() when you need the actual number.

Remember that indexes start at 0, so the last valid index is len(items) - 1. Negative indexes such as items[-1] avoid that arithmetic. The slicing lesson shows more patterns.

Python
scores = [72, 88, 95]
print(len(scores))
print(scores[len(scores) - 1])
print(scores[-1])

Why len() fails on numbers and generators

Calling len(5) raises a TypeError, because an integer is not a container. A generator also has no length, since it produces values on demand and may be infinite. If you need the count, build a list first with list(gen), or count while you loop.

Examples you can run

Press Run, then edit the code and run it again.

len() of different types

The same function counts characters, elements and keys.

len() of different types
print(len("Python"))
print(len(["pen", "book", "ruler"]))
print(len({"name": "Asha", "age": 19}))
print(len(range(0, 100, 7)))
Expected output6
3
2
15

Validate a password length

A realistic use: reject passwords that are too short.

Validate a password length
password = "tulip42"
if len(password) < 8:
    print("Too short:", len(password), "characters")
else:
    print("OK")
Expected outputToo short: 7 characters

Duplicates and accents

A set stores unique values only, and each accented letter is still one character.

Duplicates and accents
tags = ["sale", "new", "sale", "hot"]
print(len(tags))
print(len(set(tags)))
print(len("café"))
Expected output4
3
4

Common mistakes

Calling len() on an integer

✗ Wrong

count = 12345
print(len(count))
TypeError: object of type 'int' has no len()

✓ Right

count = 12345
print(len(str(count)))

Convert to a string first if you want the number of digits.

Using len() as the last index

✗ Wrong

names = ["Asha", "Ravi"]
print(names[len(names)])
IndexError: list index out of range

✓ Right

names = ["Asha", "Ravi"]
print(names[len(names) - 1])
print(names[-1])

Indexes run from 0 to len(names) - 1. Use names[-1] for the last item.

Expecting len() of a dict to count values

✗ Wrong

stock = {"apple": [1, 2, 3]}
print(len(stock))
No error, but the output is 1, not 3, because it counts keys

✓ Right

stock = {"apple": [1, 2, 3]}
print(len(stock["apple"]))

Use len(stock['apple']) to count the items inside a value.

Python len() Function: questions people ask

How do I get the length of a list in Python?

Use len(my_list). It returns the number of elements, for example len([1, 2, 3]) is 3.

Does len() count spaces in a string?

Yes. len() counts every character, including spaces and punctuation, so len('a b') is 3.

What is the time complexity of len()?

It is O(1) for built-in types, because they keep their size stored and do not count items each time.

Keep learning

Step-by-step lessons:
Python ListsPython Strings

Related:
Python range() FunctionPython sum() FunctionPython List count() MethodHow to Check if a List Is Empty in Python

More in built-in functions:
Python print() FunctionPython range() FunctionPython type() FunctionPython int() FunctionPython float() FunctionPython str() FunctionPython input() FunctionPython sum() Function See all →