Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling python function with an unknown number of arguments [duplicate]

I am writing a little script in which I call itertools.product like so:

for p in  product(list1,list2,list3):
            self.createFile(p)

Is there a way for me to call this function without knowing in advance how many lists to include?

Thanks

like image 300
Yotam Avatar asked Aug 15 '12 16:08

Yotam


People also ask

How do you pass an unknown number argument in Python?

The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-key worded, variable-length argument list. The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the word args.

How do you pass variable number of arguments to a function in Python?

As you expect it, Python has also its own way of passing variable-length keyword arguments (or named arguments): this is achieved by using the **kwargs symbol. When using **kwargs, all the keywords arguments you pass to the function are packed inside a dictionary.

How do you make an argument optional in Python?

You can define Python function optional arguments by specifying the name of an argument followed by a default value when you declare a function. You can also use the **kwargs method to accept a variable number of arguments in a function. To learn more about coding in Python, read our How to Learn Python guide .

Can a function have variable number of parameters justify?

Before Java SE 5.0, every Java method had a fixed number of parameters. However, it is now possible to provide methods that can be called with a variable number of parameters. (These are sometimes called "varargs" methods.)


2 Answers

You can use the star or splat operator (it has a few names): for p in product(*lists) where lists is a tuple or list of things you want to pass.

def func(a,b):
    print (a,b)

args=(1,2)
func(*args)

You can do a similar thing when defining a function to allow it to accept a variable number of arguments:

def func2(*args): #unpacking
   print(args)  #args is a tuple

func2(1,2)  #prints (1, 2)

And of course, you can combine the splat operator with the variable number of arguments:

args = (1,2,3)
func2(*args) #prints (1, 2, 3)
like image 59
mgilson Avatar answered Oct 16 '22 05:10

mgilson


Use the splat operator(*) to pass and collect unknown number of arguments positional arguments.

def func(*args):
   pass

lis = [1,2,3,4,5]
func(*lis)
like image 44
Ashwini Chaudhary Avatar answered Oct 16 '22 05:10

Ashwini Chaudhary