Why doesn't following code print anything:
#!/usr/bin/python3
class test:
def do_someting(self,value):
print(value)
return value
def fun1(self):
map(self.do_someting,range(10))
if __name__=="__main__":
t = test()
t.fun1()
I'm executing the above code in Python 3. I think i'm missing something very basic but not able to figure it out.
I just want to add the following:
With multiple iterables, the iterator stops when the shortest iterable is exhausted
[ https://docs.python.org/3.4/library/functions.html#map ]Python 2.7.6 (default, Mar 22 2014, 22:59:56)
Python 3.4.0 (default, Apr 11 2014, 13:05:11)
That difference makes the answer about simple wrapping with
list(...)
not completely correctThe same could be achieved with:
map()
returns an iterator, and will not process elements until you ask it to.Turn it into a list to force all elements to be processed:
or use
collections.deque()
with the length set to 0 to not produce a list if you don't need the map output:but note that simply using a
for
loop is far more readable for any future maintainers of your code:Before Python 3, map() returned a list, not an iterator. So your example would work in Python 2.7.
list() creates a new list by iterating over its argument. ( list() is NOT JUST a type conversion from say tuple to list. So list(list((1,2))) returns [1,2]. ) So list(map(...)) is backwards compatible with Python 2.7.