Optimizing Loops In Python With Map

pradeep's Avatar author of Optimizing Loops In Python With Map
This is an article on Optimizing Loops In Python With Map in Python.
Rated 5.00 By 5 users
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: Python
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: Python
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: Python
newlist = [s.upper() for s in list]