I have a function that uses *args
to accept a variable number of arguments. I want to, similarly, pass a variable number of arguments (say, from a list or tuple). How does this work in Python?
For example, if I have
def product(*args):
res = 1
for x in args:
res *= x
return res
and a list a
, how can I use this function to get the product of all the values in a list, without having to write out product(a[0], a[1], ..., a[N-1])
longhand?
I understand that I could just write the function to accept a single list argument, but I want to understand how this works in general.
I was only able to solve the problem by dynamically generating code and using eval()
. Surely there's a better way?