0

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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Jake
  • 113
  • 2
  • You can explode a slice: `product(*a[:3])` <-- this will have the same effect as `product(a[0], a[1], a[2])` – Mathias R. Jessen Jan 24 '23 at 15:25
  • Welcome to Stack Overflow. Aside from this being a common duplicate - please read [ask] and note well that this is **not a discussion forum**. We want questions to be much more direct, clear, explicit and **not conversational**. I edited the question to show an example of good style for Stack Overflow questions. In particular, while it's good to [do research](https://meta.stackoverflow.com/questions/261592), the question should only show results from research that are **relevant to understanding the question**. (Also, because this is not a discussion forum, we do not have "threads" here.) – Karl Knechtel Jan 24 '23 at 15:39

1 Answers1

0

* is also used to unpack an iterable into individual arguments.

Given the definition of product, calling with a list is as simple as:

print(product(*[1,2,3])) # 6
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • Though the question is a duplicate, I put effort into cleaning up the Q&A because I suspect that it can make a good signpost. – Karl Knechtel Jan 24 '23 at 15:44