User Controls

What does `map()` do that a `for` loop doesn't?

  1. #1
    Sophie Pedophile Tech Support
    I always use a `for` loop. How are they different and when should i use what?
  2. #2
    aldra JIDF Controlled Opposition
    what language? I thought map was a datatype like an array, you can use for to iterate over it
  3. #3
    Sophie Pedophile Tech Support
    Originally posted by aldra what language? I thought map was a datatype like an array, you can use for to iterate over it

    Python of course.
  4. #4
    Lanny Bird of Courage
    So the literal answer is that`map(...)` is an expression (it evaluates to some value) while `for ... in ...: ...` is a statement, that is you cant do something like:


    new_list = for x in range(10): x+1


    although you can


    new_list = []
    for x in range(1): new_list.append(x+1)


    but


    new_list = map(range(10), lambda x: x+1)


    does work.

    The better answer is that they convey a different intention. `map()` indicates you're creating a new sequence with a 1:1 correspondence with its first argument, to do anything else with it would be really bad style. A for loop can be used to create a new sequence with a 1:1 correspondence with the thing being iterated over, but it can be used in a more general way as well. For example you could do something like:


    for filename in files_to_make:
    f = open(filename, 'w')
    f.write('lol\n')
    f.close()


    This doesn't produce a new list, it takes some action with side effects for each item in an input sequence. By contrast map is much more constrained, it always produces a new list and it will always have the same length as the input list.

    You might wonder why we would ever use a less powerful construct like map. The main reason is that it conveys meaning better, because there are fewer things you can do with it, it's more obvious what you intend when you use it. Compare with while vs. for loops. While is a more powerful construct, it can be used to iterate over a sequence like for, but it can also loop indefinitely until some condition is met. We prefer for however because it makes it explicit what exactly we're iterating over. Likewise map makes it explicit that you're producing a new bijective sequence from an existing one. You can also use the length equality and callback convention for some optimizations like preallocation and memoization, but that's kind of an aside, not every language that implements lisp map (python's map is inherited from lisp) does this.
    The following users say it would be alright if the author of this post didn't die in a fire!
Jump to Top