9

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

Yotam
  • 9,789
  • 13
  • 47
  • 68
  • 1
    This is not the same question as how to "Unpack a list in Python". Unpacking a list is the *answer* to this question, not the *question*. – divenex Jan 17 '20 at 15:36

2 Answers2

22

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)
mgilson
  • 300,191
  • 65
  • 633
  • 696
4

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)
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504