Vectors the Pythonic Way

Photo by George Pagan III on Unsplash

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.

--

--

--

Reject the null hypothesis

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Insurance Dao Tester Experience

What I’ve learned from multiple migration projects

NKN Bi-weekly Report Jan 1–15, 2020

Orbiter Finance: a cross-rollup bridge aims to be infrastructure in L2

How it works in java. Thread Pool.

Introducing Wraith Bank

Sunak row: Reveal all about ministers’ personal tax, says Starmer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mansoor Aldosari

Mansoor Aldosari

Reject the null hypothesis

More from Medium

Revisiting Linear Algebra with image filters and python

confused filenotfound or file not created in the place you expect(Python)

Central Limit Theorem and Chebyshev’s Inequality

How to generate random numbers?(Linear Congruential Generator)