Editor

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

Broken
pin = 48213
print(len(pin))
Output
Traceback (most recent call last):
  File "<exec>", line 2, in <module>
TypeError: object of type 'int' has no len()

The fix

Fixed
pin = 48213
print(len(str(pin)))
Output
5

A number has no length, but its string does: str(48213) has 5 characters.

Try fixing it yourself in the editor

2. Saving the result of `.append()`

This raises the error

Broken
names = ["Ada", "Alan"]
names = names.append("Grace")
print(len(names))
Output
Traceback (most recent call last):
  File "<exec>", line 3, in <module>
TypeError: object of type 'NoneType' has no len()

The fix

Fixed
names = ["Ada", "Alan"]
names.append("Grace")
print(len(names))
Output
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.

Try fixing it yourself in the editor

3. Calling `len()` on a `map()` result

This raises the error

Broken
numbers = map(int, "4 8 15".split())
print(len(numbers))
Output
Traceback (most recent call last):
  File "<exec>", line 2, in <module>
TypeError: object of type 'map' has no len()

The fix

Fixed
numbers = list(map(int, "4 8 15".split()))
print(len(numbers))
Output
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.

Try fixing it yourself in the editor

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 without return.
  • Wrap map(), filter(), zip() and generators in list() before counting.

All Python errors · How to read a traceback · Step through your code