I've been a procedural programmer for a while now, and just trying to switch my mindset to use functional programming (in Python 3 for now).
So, instead of writing a for-each loop, I'm trying to grasp the interaction between map and list(map(..))
Lets say I have a simple for-in loop which does some resource heavy computation (which I'll replace with print here for the sake of simplicity):
arr = [1,2,3,4]
for x in arr:
print(x)
Now, when I try to do the following
map(lambda x: print(x), arr)
nothing happens, UNTIL, i wrap this in a list and it does my super heavy print function:
list(map(lambda x: print(x), arr))
Why? What am I missing? I understand map returns an iterator which is supposed to save memory instead of just holding the entire list right away. But when is my super heavy print function going to be triggered then?
listwrapper? Because I have to trigger it through the iterator?mapis what's commonly know as being lazy. It won't do any work (i.e. call you function to compute any values) unless it has to. You can force map to compute a single value usingnext. When you cast themapiterator to be alisthowever, you're forcingmapto compute all of its values and thus call your function.next(some_iterator)on it to consume the next value, one by one. Until all values are consumed. Applyinglistto it will make it for all the values and returns you a list with all the iterator values. Or you can use a for loop