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.
Python calls the function once for every item in the iterable we pass into map() and it returns the manipulated item within a map object. For the first function argument, we can either pass a user-defined function or we can make use of lambda functions, particularly when the expression is less complex.
Map in Python is a function that works as an iterator to return a result after applying a function to every item of an iterable (tuple, lists, etc.). It is used when you want to apply a single transformation function to all the iterable elements. The iterable and function are passed as arguments to the map in Python.
To use the map() function, attach it to an array you want to iterate over. The map() function expects a callback as the argument and executes it once for each element in the array. From the callback parameters, you can access the current element, the current index, and the array itself.
map() creates a new array from calling a function for every array element. map() calls a function once for each element in an array. map() does not execute the function for empty elements.
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:
list(map(self.do_someting,range(10)))
or use collections.deque()
with the length set to 0 to not produce a list if you don't need the map output:
from collections import deque deque(map(self.do_someting, range(10)))
but note that simply using a for
loop is far more readable for any future maintainers of your code:
for i in range(10): self.do_someting(i)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With