简体   繁体   中英

Passing List to Function in place of Many Arguments

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?

You can use extended iterable unpacking operator .

def func(x, a, b):
    return a*x + b*b

c = [2, 3]
func(x,*c) 

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM