Search code examples
pythonarraysargumentsnamedtuple

Can I use `namedtuple` to give names to the elements of a 1D array?


res.x is an array I obtained by optimizing an objective function, and I want to give each element a name so I can use them more conveniently later. My initial idea is to use namedtuple, but apparently Python would just take the array as the first argument and reports the rest missing. Is there a way out? Can somebody help me?

from collections import namedtuple

Coef = namedtuple("Coefficients", ["alpha","beta","gamma"])
t = Coef(res.x)

Traceback (most recent call last):

File "< stdin >", line 1, in < module >

TypeError: __new__() missing 2 required positional argument: 'beta', 'gamma'


Solution

  • from collections import namedtuple
    
    Coef = namedtuple("Coefficients", ["alpha","beta","gamma"])
    t = Coef(*res.x)
    

    By putting an * in front of the list, python's going to split the array in 3 differents arguments.