Vectors the Pythonic Way
There are many ways to achieve the same task in python, but there is a preferred way. For your code to be pythonic, it should comply with the zen of python (PEP20).
import this
Setup:
Let us have a look at three different ways to sum vectors (a vector is a list of floats):
vectors = [[1.5, 2.5, 3.5],
[3.5, 4.5, 5.5],
[5.5, 6.5, 7.5],
[7.5, 8.5, 9.5]]
Note: vectors are of equal length.
The pythonic way:
[sum(vector[i]
for vector in vectors)
for i in range(len(vectors[0]))] # -> [18.0, 22.0, 26.0]
This way utilizes comprehension lists. It’s explicit and readable.
The non-pythonic way:
res = []
for i in range(len(vectors[0]):
temp = 0
for vector in vectors:
temp += vector[i]
res.append(temp)res # -> [18.0, 22.0, 26.0]
This way is explicit because it uses for loops. But when it comes to python, there should be one and only one preferable way.
The functional way:
from functools import reducelist(map(sum, zip(*vectors))) # -> [18.0, 22.0, 26.0]
This way is implicit since a functional line of codes tends to be declarative.
I hope this gave you a broad perspective of different ways to achieve the same task. Moreover, the pythonic way is not black or white; for example, the non-pythonic way is pythonic to an extent, but since there is a better way (comprehension lists), it took second place.