Go4Expert (http://www.go4expert.com/)
-   Python (http://www.go4expert.com/articles/python-tutorials/)
-   -   Optimizing Loops In Python With Map (http://www.go4expert.com/articles/optimizing-loops-python-map-t6251/)

pradeep 7Sep2007 22:38

Optimizing Loops In Python With Map
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:

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]

All times are GMT +5.5. The time now is 06:02.