7

How would I pass an unknown number of parameters into a function? I have a function defined in the following way

def func(x, *p):
    # do something with variable number of parameters (*p)
    pass

I'm trying to pass in a list of values to use as parameters. I tried using a list and a tuple but the function always returns zero. Has anyone got any advice?

Community
  • 1
  • 1
knw500
  • 512
  • 2
  • 8
  • 15

2 Answers2

21
some_list = ["some", "values", "in", "a", "list", ]
func(*some_list)

This is equivalent to:

func("some", "values", "in", "a", "list")

The fixed x param might warrant a thought:

func(5, *some_list)

... is equivalent to:

func(5, "some", "values", "in", "a", "list")

If you don't specify value for x (5 in the example above), then first value of some_list will get passed to func as x param.

frnhr
  • 12,354
  • 9
  • 63
  • 90
  • Hy, do you have an idea of how to do something like: func(first="some", name="values", third="in", another="a", last="list") from a list some_list = [(attr_1, value1), (attr2, value2), ...] or a dict ? – Hedwin Bonnavaud Feb 04 '22 at 09:52
7

Pass the values as comma separated values

>>> def func(x, *p):           # p is stored as tuple
...     print "x =",x
...     for i in p:
...         print i
...     return p
... 
>>> print func(1,2,3,4)        # x value 1, p takes the rest
x = 1
2
3
4
(2,3,4)                        # returns p as a tuple

You can learn more by reading the docs

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140