TypeError: object of type 'int' has no len()
TypeError: object of type 'int' has no len() in Python means len() only measures things that contain items: strings, lists, dicts, sets. You gave it a number, or None.
How do I fix TypeError: object of type 'int' has no len()?
TypeError: object of type 'int' has no len() means you passed a number to len(). len() only works on things with items, like strings, lists and dicts. To count digits, write len(str(n)). If the variable should hold a list, find where it was overwritten with a count, such as items = len(cart).
- 1. Print the typePrint type(x) just before len(x). int or float means a number; NoneType means a missing return.
- 2. Variable reused for a countLook for an earlier x = len(...) that replaced the list. Store the count in its own variable.
- 3. Counting digitsNumbers have no length. Convert first: len(str(12345)) gives 5.
What does TypeError: object of type 'int' has no len() mean?
A number is a single value with no items, so it has no length. Usually you wanted the number of digits (convert to text first), or the variable holds a count where you expected the collection. The 'NoneType' version means a function returned None.
Why does TypeError: object of type 'int' has no len() happen?
1. Counting the digits of a number
Measure the text form, not the number.
Breaks
digits = len(12345)Works
digits = len(str(12345))2. A count stored where the list was expected
The variable was reused for len() of the list earlier.
Breaks
items = len(cart)
if len(items) > 0:
...Works
count = len(cart)
if count > 0:
...3. A function that returned None
A function with no return statement returns None.
Breaks
def load_rows():
rows = read()
len(load_rows())Works
def load_rows():
rows = read()
return rowsHow to find it in your own code
Print type(x) right before len(). If it is int or float, decide what you meant to measure: digits, or the collection the number came from. If it is NoneType, find the function that produced it and its missing return.
Try it: fix this bug
easycount_active_users([{'active': True}]) raises TypeError: object of type 'filter' has no len().
def count_active_users(users):
active = filter(lambda u: u.get("active"), users)
return len(active)More challenges with this error
Each of these challenges runs into this error. Find the bug and fix it, no install and no account needed.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.