0

I'm curious if there is a way to provide an arbitrary number of parameters to a function. Viz.

def sum2(*args):
    return sum2(args)

input = [1, 2, 3, 4, 5]
sum2(1, 2, 3, 4, 5)
sum2(input)

Or pass the values in array "input" to the function such that the two calls are the same. I know there is an easy workaround for the particular example, but, in general, is this possible?

Edit: Corrected example

jshackle
  • 117
  • 8
  • 1
    You can also use the star when calling the function: https://stackoverflow.com/a/36926/14215102 –  Jun 17 '21 at 12:11
  • 1
    Beware that 'in' is a reserved keyword in Python. You have to call your 'in' variable differently. On line 5, you make a boolean comparison but don't assign the result to a variable, that probably also returns an error. – DSteman Jun 17 '21 at 12:11
  • Does this answer your question? [What does \*\* (double star/asterisk) and \* (star/asterisk) do for parameters?](https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters) – JonSG Jun 17 '21 at 13:29

1 Answers1

0

Definition

*args allows for any number of optional positional arguments (parameters), which will be assigned to a tuple named args.

**kwargs allows for any number of optional keyword arguments (parameters), which will be in a dict named kwargs.

The use of '*' operator and '**' operator in function call.

unpacking my_tuple with '*' same unpacking my_list with '*'

Example:

def sum(a,b):
    print(a+b)

my_tuple = (1,5)
my_list = [1,5]
my_dict = {'a':1,'b':5}

# Let us unpack data structure of list or tuple or dict into arguments with help of '*' operator
sum(*my_tuple)   # becomes same as sum(1,2) after unpacking my_tuple with '*'
sum(*my_list)    # becomes same as sum(1,2) after unpacking my_list with  '*'
sum(**my_dict)   # becomes same as sum(a=1,b=2) after unpacking by '**' 

Output:

6
6
6
Salio
  • 1,058
  • 10
  • 21