1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

Optimizing Loops In Python With Map

Discussion in 'Python' started by pradeep, Sep 7, 2007.

  1. pradeep

    pradeep Team Leader

    Apr 4, 2005
    Likes Received:
    Trophy Points:
    Kolkata, India
    Home Page:
    Python supports a couple of looping constructs. The for statement is most commonly used. It loops over the elements of a sequence, assigning each to the loop variable. If the body of your loop is simple, the interpreter overhead of the for loop itself can be a substantial amount of the overhead. This is where the map function is handy. You can think of map as a for moved into C code. The only restriction is that the "loop body" of map must be a function call.

    Here's a straight forward example. Instead of looping over a list of words and convert ing them to upper case:
     newlist= []
     for word in list:
    you can use map to push the loop from the interpreter into compiled C code:
     import string
     newlist = map(string.upper, list)
    List comprehensions were added to Python in version 2.0 as well. They provide a syntactically more compact way of writing the above for loop:
     newlist = [s.upper() for s in list]

Share This Page