0

I'm trying to create a list of names for my parameters that I want a function to take. The length should be 32 and I want something like bs=[b0,b1,b2,...,b31] but I don't want to write in b0,b1,... for the hand so is there any way to write a small programme in Python that can generate such a list?

EDIT: Is there anyway to make the parameter values not be strings? I'm trying to put them as arguments in a function like so:

def chiwork(a0,a1,a2,a3,bs):
    ana=np.array([a0,a1,a2,a3])
    betalat=[0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3]
    chia=sum((ana-a)**2)+sum((bs*a[betalat]-amssr)**2)
    return chia

The function needs to "know" that there are 32 bs but there is no way to unpack it when the elements in bs are in a list.

fountainhead
  • 3,584
  • 1
  • 8
  • 17
Linus
  • 147
  • 4
  • 15
  • I think you're looking for `*args` and `**kwargs`. See [Can a variable number of arguments be passed to a function](https://stackoverflow.com/questions/919680/can-a-variable-number-of-arguments-be-passed-to-a-function). – TrebledJ Mar 02 '19 at 09:09

2 Answers2

2

Use list comprehension:

bs=['b'+str(i) for i in range(32)]
msi_gerva
  • 2,021
  • 3
  • 22
  • 28
1

I think this meets all your requirements, making generous use of Python's data model for function objects:

def my_func (b1, b2, b3, a1, a2, a3):

    par_names = my_func.__code__.co_varnames[:6]    # A tuple of strings of all param names
                                                    # It's ok to hard-code 6.
    local_ns = locals()
    par_vals  = [local_ns[x] for x in par_names]    # A list of all param values

    another_func(par_vals[0], par_vals[3])
    another_func(*par_vals[0:2])                    # Unpacking first 2 params

def another_func(param1, param2):
    print ("Inside another_func, (param1, param2) are:", param1, ",", param2)

my_func(10, 20, 30, 40, 50, 60)

Output:

Inside another_func, (param1, param2) are: 10 , 40
Inside another_func, (param1, param2) are: 10 , 20

Notes:

  1. No need to follow naming conventions like b1, b2, for param names.
  2. Works for any number of parameters (not just the 32 in your example).
  3. Works even if some of the parameters are kwargs.
  4. As documented, __code__.co_varnames will contain the parameter names, followed by local variable names. Hence we're indexing for the first 6 elements, to get only the parameter names.
fountainhead
  • 3,584
  • 1
  • 8
  • 17