Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Jonathan Zerger
The Python "TypeError: object of type 'map' has no len()" occurs when we pass
a map
object to the len()
function. To solve the error, convert the map
object to a list before passing it to len
, e.g. len(list(my_map))
.
Here is an example of how the error occurs.
my_list = ['1', '2', '3'] my_map = map(int, my_list) # ⛔️ TypeError: object of type 'map' has no len() print(len(my_map))
We can't pass a map
object to the len()
function but we can convert it to a
list
and get the length of the list.
my_list = ['1', '2', '3'] # ✅ convert to list my_new_list = list(map(int, my_list)) print(len(my_new_list)) # 👉️ 3
The list class takes an iterable and returns a list object.
Note that passing the map
object to the list
class exhausts the iterator.
my_list = ['1', '2', '3'] my_map = map(int, my_list) print(list(my_map)) # 👉️ [1, 2, 3] print(list(my_map)) # 👉️ []
So if you convert a map object to a list, do it directly and not in multiple places.
The map() function takes a function and an iterable as arguments and calls the function on each item of the iterable.
When we pass an object to the len() function, the object's __len__() method is called.
You can use the dir()
function to print an object's attributes and look for
the __len__
attribute.
my_list = ['1', '2', '3'] my_map = map(int, my_list) print(dir(my_map))
Or you can check using a try/except
statement.
my_list = ['1', '2', '3'] my_map = map(int, my_list) try: print(my_map.__len__) except AttributeError: # 👇️ this runs print('object has no attribute __len__')
We try to access the object's __len__
attribute in the try
block and if an
AttributeError
is raised, we know the object doesn't have a __len__
attribute and cannot be passed to the len()
function.
The len() function returns the length (the number of items) of an object.
my_list = ['apple', 'banana', 'kiwi'] result = len(my_list) print(result) # 👉️ 3
If you aren't sure what type a variable stores, use the built-in type()
class.
my_list = ['1', '2', '3'] print(type(my_list)) # 👉️ <class 'list'> print(isinstance(my_list, list)) # 👉️ True my_map = map(int, my_list) print(type(my_map)) # 👉️ <class 'map'> print(isinstance(my_map, map)) # 👉️ True
The type class returns the type of an object.
The isinstance
function returns True
if the passed in object is an instance or a subclass of
the passed in class.