No. 6
You can use the map function to perform the same operation on every element of an array: a list, a tuple, or even a string, as long as it can be iterated. It returns a new iterable map object containing the data that the function has operated on.
Suppose you wanted to square every element of a numerical array. You could write a sq function:
def sq(x):
return x*x
and then use the map function to carry out the operation on the whole array. It returns a map object you can iterate through.
ara=[2,3,6,8,5,4]
amap = map(sq, ara)
# iterate through output map
for x in amap:
print(x)
Or, more commonly, you can convert it to a List, Tuple or Set using the list(), tuple() or set() functions. For example:
ara1 = list(amap)
print (amap)
will produce a list.
[4, 9, 36, 64, 25, 16]
Using the map function can be somewhat faster than looping through the array yourself. The equivalent code without the map function is:
ara = [2,3,6,8,5,4]
amap = []
for a in ara:
amap.append(sq(a))
If you time these two approaches, running each loop 1 million times, you get
Map function loop: 1.19 secs
For loop: 1.53 seconds
making the map function about 22% faster.
And how did we do this timing? It is as easy as you think:
start = datetime.now()
for i in range (0, 1000000):
ara=[2,3,6,8,5,4]
amap = map(sq, ara)
ara1 = list(amap)
endt = datetime.now()
print("time=", endt-start)
Make it even faster
There is a way to make Python programs a lot faster: the pypy3 compiler. This is a Just-In-Time (JIT) compiler that analyzes the code during execution to determine where speedup might occur by compiling the code on the spot. You can install Pyp3 yourself and run it on this code. You will need to unzip the download into a convenient location and add that path to your PATH variable. Then, you can just type
pypy3 maptest.py
The resulting timing on our machine is faster, but a little surprising:
Map function loop: 0.125 sec (9.52 times faster)
For loop: 0.062 sec (24.6 times faster)
In other words the pypy3 JIT compiler works better on the standard code than with the map function included. But either way, pypy3 is a good speedup solution.
All code can be downloaded from GitHub under jameswcooper/newsletter.
Subscribe to this newsletter so you don’t miss a single Monday’s issue!