Object of type map has no len() in Python 3
Object of type map has no len() in Python 3
In Python 3, map
returns a map object not a list
:
>>> L = map(str, range(10))
>>> print(L)
<map object at 0x101bda358>
>>> print(len(L))
Traceback (most recent call last):
File <stdin>, line 1, in <module>
TypeError: object of type map has no len()
You can convert it into a list then get the length from there:
>>> print(len(list(L)))
10
While the accepted answer might work for the OP, there are some things to learn here, because sometimes you cant find the length even with doing the OPs map(modify_word, wordlist)
casted into list and checking the length with len(list(map(modify_word, wordlist)))
. You cant because sometimes the length is infinite.
For example lets consider the following generator that lazy calculate all the naturals:
def naturals():
num = 0
while True:
yield num
num +=1
And lets say I want to get the square of each of those, that is,
doubles = map(lambda x: x**2, naturals())
Note that this is a completely legit use of map function, and will work, and will allow you to use next() function on the doubles
variable:
>>> doubles = map(lambda x: x**2, naturals())
>>> next(doubles)
0
>>> next(doubles)
1
>>> next(doubles)
4
>>> next(doubles)
9
...
But, what if we try to cast it into a list? Obviously python cant know if we are trying to iterate through a never-ending iterator. So if well try to cast an instance of this mapObject to a list, python will try and keep trying and will get stuck on an infinite loop.
So when you cast to list, you should first make sure you know your map object will indeed yield finite number of elements.