Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 Map function is not Calling up function

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.

like image 743
Sibi Avatar asked Nov 29 '12 10:11

Sibi


People also ask

How do you call a function from a map in Python?

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.

How does map function work in Python?

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.

How do you use a function on a map?

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.

What is the map () function and how does it work?

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.


2 Answers

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) 
like image 183
Martijn Pieters Avatar answered Sep 18 '22 00:09

Martijn Pieters


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.

like image 24
bootchk Avatar answered Sep 20 '22 00:09

bootchk