Tips for program optimization
Next, let's take a look at some generic tips to optimize your programs.
Using filter and map
Python provides two built-in functions named filter and map to manipulate collections directly rather than having to iterate over each item in the collection. The filter, map, and reduce functions are faster than loops because a lot of the work is done by the underlying code written in C. The filter and map functions can be explained as follows:
- The
filter(function, list) function returns a list (iterators in Python 3.x) that contains all the items for which the function returns atruevalue. The following command is an example:print filter(lambda num: num>6, range(1,10))# prints [7, 8, 9]
This is faster than running a conditional
if-thencheck against the list. - The
map(func, list)function appliesfuncto each item in the list and returns the values in a new list (returns iterators instead of lists in Python 3.x). The following command is an example:print map(lambda...