Optimizing Loops In Python With Map

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

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    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:
    Code:
     newlist= []
     for word in list:
       newlist.append(word.upper())
     
    you can use map to push the loop from the interpreter into compiled C code:
    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:
    Code:
     newlist = [s.upper() for s in list]
     
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice