TypeError: object of type 'int' has no len()
What it means
len() counts the items in a collection, such as a string, list or dictionary. You gave it something that has no items to count, here a number. The type in the message tells you what you passed instead.
1. Counting the digits of a number
This raises the error
Traceback (most recent call last): File "<exec>", line 2, in <module> TypeError: object of type 'int' has no len()
The fix
5
A number has no length, but its string does: str(48213) has 5 characters.
2. Saving the result of `.append()`
This raises the error
Traceback (most recent call last): File "<exec>", line 3, in <module> TypeError: object of type 'NoneType' has no len()
The fix
3
.append() changes the list in place and returns None, which replaced the list. The message for this one says 'NoneType'. Call .append() on its own line.
3. Calling `len()` on a `map()` result
This raises the error
Traceback (most recent call last): File "<exec>", line 2, in <module> TypeError: object of type 'map' has no len()
The fix
3
map() produces items one by one and does not know how many there are. Wrapping it in list() collects them, and a list has a length. filter(), zip() and generators work the same way.
When you see this error, check
- Read the type in the message: it tells you what you passed to
len(). - For the number of digits, use
len(str(n)). - If the type is
NoneType, look for a saved result of.append(),.sort()or a function withoutreturn. - Wrap
map(),filter(),zip()and generators inlist()before counting.
Related errors
All Python errors · How to read a traceback · Step through your code