TypeError: object of type 'map' has no len() Python3

依然范特西╮ 提交于 2019-12-02 13:13:53

You are getting this error because you are trying to get len of map object (of generator type) which do not supports len. For example:

>>> x = [[1, 'a'], [2, 'b'], [3, 'c']]

# `map` returns object of map type
>>> map(lambda a: a[0], x)
<map object at 0x101b75ba8>

# on doing `len`, raises error
>>> len(map(lambda a: a[0], x))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'map' has no len()

In order to find the length, you will have to type-cast the map to list (or tuple) and then you may call len over it. For example:

>>> len(list(map(lambda a: a[0], x)))
3

Or it is even better to simply create a list using the list comprehension (without using map) as:

>>> my_list = [a[0] for a in x]

# since it is a `list`, you can take it's length
>>> len(my_list)
3
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!