-1

NumPy arrays are extremely convenient for expressing many common vector and array operations. The standard notation is:

import numpy as np

v = np.array([1, 2, 3, 4])
u = np.array([0.3, 0.4, 0.5])

I have many cases where I need a lot of different short np.array vectors and the boilerplate np.array(...) gets in a way of clarity. What are the practical solutions people use to reduce boilerplate in these cases? Is there any Python magic to help? Ideally, I would like to be able to write something along these lines:

v = <1, 2, 3, 4>
u = <0.3, 0.4, 0.5>

<> is just a random choice for illustration purpose.

Paul Jurczak
  • 7,008
  • 3
  • 47
  • 72
  • 2
    Unlike some other languages, python doesn't allow us to play with the syntax much, or to redefine the use of operators. Obviously you can define aliases for `np.array`, but it still be a function. `numpy/lib/index_tricks.py` has some examples of defining classes so we can use index notation instead of functions, e.g. `np.r_[1,2,3,4]` – hpaulj Dec 25 '21 at 22:07

2 Answers2

2

You can make a class and a corresponding instance with a single letter identifier defining its __getitem__ method to allow use of brackets in defining the numpy array shorthand:

import numpy as np

class Ä:
    def __getitem__(self,index):
        return np.array(index)
Ä = Ä()

usage:

V = Ä[1,2,3]

print(V,type(V)) # [1 2 3] <class 'numpy.ndarray'>

M = Ä[ [1,2,3],
       [4,5,6] ]

print(M)
[[1 2 3]
 [4 5 6]]
Alain T.
  • 40,517
  • 4
  • 31
  • 51
1

You can use import like below:

from numpy import array as _

v = _([1, 2, 3, 4])
u = _([0.3, 0.4, 0.5])

Shorter:

import numpy as np

def _(*args, **kwargs)
    return np.array(args, **kwargs)

v = _(1, 2, 3, 4)
u = _(0.3, 0.4, 0.5)

Or you can use a lambda function: _ = lambda *args, **kwargs: np.array(args, **kwargs)

Update: add kwargs arguments by @Jasmijn

Corralien
  • 109,409
  • 8
  • 28
  • 52
  • 2
    `_` is a somewhat dangerous choice given that it is often used to store unused unpacked values. You can use any other valid identifier though ( e.g. `Ä(1,2,3)`) – Alain T. Dec 25 '21 at 21:50
  • @AlainT. I know that. However, the OP wants clarity. The `_` is the only character in python that allows this construction. – Corralien Dec 26 '21 at 07:48