Reputation: 243
First, I apologize if a similar question has been addressed. I looked but had no luck (which could be from me not knowing how to properly search for this question.) In it's simplest form, suppose we have the following:
def func(x, a, b):
return a*x + b*b
c = [2, 3]
How would you use the function like, func(x, c)
? Specifically, rather than writing out an entire array's elements as arguments to a function, how do you cleanly in place of the arguments reference an array?
Upvotes: 2
Views: 53
Reputation: 48437
You can use extended iterable unpacking operator.
def func(x, a, b):
return a*x + b*b
c = [2, 3]
func(x,*c)
Upvotes: 2
Reputation: 35
The answer might be: Packing
When we don’t know how many arguments need to be passed to a python function, we can use Packing to pack all arguments in a tuple.
# A Python program to demonstrate use
# of packing
# This function uses packing to sum
# unknown number of arguments
def mySum(*args):
sum = 0
for i in range(0, len(args)):
sum = sum + args[i]
return sum
# Driver code
print(mySum(1, 2, 3, 4, 5))
print(mySum(10, 20))
Upvotes: 1