0

I am getting an array of values and I want to send them to a predefined function with the same parameter count.

The naive way is to do:

 values = [1,2,3,4] # getting it from outside
 if len(values) == 1:
     func(values[0])
 elif len(values) == 2:
     func(values[0], values[1])
 .
 .
 .

is there more elegant way ?

1
  • func(values) ? Commented Jun 20, 2019 at 12:25

1 Answer 1

2

You can use arbitrary argument lists

def func(*args):

    for arg in args:
        print(arg)

values = [1]
func(*values)
values = [1, 2]
func(*values)

func(1)
func(1,2)

The output will be

1
1
2

Or just pass the entire array to the function via func(values)

def func(values):

    for value in values:
        print(value)

values = [1]
func(values)

values = [1, 2]
func(values)
Sign up to request clarification or add additional context in comments.

3 Comments

Not necessarily when you can do just func(values).
My problem is that the function can be: def func(a): or def func(a,b): etc so I I call func I won't have to do the if else over the array size, but just call func with the array and it will know how to put array[0] in a var and array[1] in b var automatically
So you have variable arguments, func(a) till func(a,b,c,d) ? well you would need some kind of conditional to identify how many arguments are being passed, or you would need an intermediate functions which can do that for you @asaf You can't really avoid this where number of arguments are variable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.