Python len() Function
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.
| Syntax | len(obj) |
|---|---|
| Parameters | obj: a sequence (string, list, tuple, range, bytes) or a collection (dict, set) |
| Returns | An int that is 0 or greater |
| Time complexity | O(1): the size is stored, not counted on each call |
What len() counts for each data type
| Type | What is counted | Example | Result |
|---|---|---|---|
str | Characters (Unicode code points) | len('Python') | 6 |
list | Elements | len([4, 8, 15]) | 3 |
tuple | Elements | len((1, 2)) | 2 |
dict | Keys (one per key-value pair) | len({'a': 1, 'b': 2}) | 2 |
set | Unique elements | len({1, 1, 2}) | 2 |
range | Numbers produced | len(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.
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.
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.
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.
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))✓ 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)])✓ 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))✓ 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 →