1

Is there a way to build a list of the arguments to python function to use it inside the function? For example:

def sum_of_middle_three(score1,score2,score3,score4,score5):
"""
Find the sum of the middle three numbers out of the five given.
"""
sum = (score1+score2+score3+score4+score5)
return sum

How to refer to the input argument list in the function, if possible this gives possibility to call that function by variable argument list

2 Answers2

2

You can use *args and **kwargs

*args and **kwargs allow you to pass a variable number of arguments to a function.

Example:

In [3]: def test(*args):
   ...:         return sum(args)
   ...:
   ...:

In [4]: test(1, 2, 3, 4)
Out[4]: 10

In [5]:

Addtionally if you want to preserve name of the argumenets use **kwargs,

Example:

In [10]: def tests(**kwargs):
    ...:     print(kwargs)
    ...:     return sum(kwargs.values())
    ...:
    ...:

In [11]: tests(a=10, b=20, c=30)
{'a': 10, 'c': 30, 'b': 20}
Out[11]: 60

In [12]: 
Nishant Nawarkhede
  • 8,234
  • 12
  • 59
  • 81
1

You can use *args

def f(*args):
    return(sum(args))

>>>f(1,2,3,4)
10

>>>f(1,2)
3
rafaelc
  • 57,686
  • 15
  • 58
  • 82