0

In python, I try to do this:

a=[1,2]
b=[3,4]
c=[5,6]
full=[]
for i in a:
    for j in b:
        for k in c:
            full.append(i,j,k)

to get all possible combinations from list a,b,c and write into another list, it works fine. My question is: what should I do if there is unknown number of lists,such as

a = ([1,2]),b,c,d,e......

I am also aware there is itertools module can help, I need to use itertools.product, which can take multiple arguments, but I dont know how to put all arguments in there. Any help will be appreciated.

I know my code above is the same as: list(itertools.product(a,b,c)) But I would like to know how to put unknown number of arguments in there. There might be more lists, and they might be different in length, and they have no patterns, so the 'repeat' or 'range' won't work either.

Zimo Yin
  • 1
  • 1
  • last code line should be full.append([i,j,k]), sorry – Zimo Yin Jan 08 '16 at 18:14
  • 1
    `full = list(product(a, b, c))` – Hugh Bothwell Jan 08 '16 at 18:20
  • @Kasramvd Is this really a dupllicate? The OP is asking *how* to use `itertools.product` here, for an unknown number of arguments. – timgeb Jan 08 '16 at 18:21
  • @HughBothwell *unknown number of lists* – timgeb Jan 08 '16 at 18:31
  • @HughBothwell Thank you for replying. I know that would work, but my question is what should I do if I have unknown number of list. How should I write the statement if there is possible e,f and g etc. – Zimo Yin Jan 08 '16 at 18:32
  • 2
    Since the question is closed I can only give you a very short answer in the comments. You need a collection of your unknown number of lists and pass that to `itertools.product` with the `*args` syntax, i.e. if `s` is your lists of lists, you would use `list(itertools.product(*s))`. When passing an argument to a function in this way, all the values in the sequence are unpacked and passed as if they were separate arguments. Try it for `s=[a,b,c]`. Hope this helps, I'm running out of characters. – timgeb Jan 08 '16 at 18:37
  • @timgeb There is no way for that, the only way is putting all that list in another list an use unpacking operation. `product(*main_list)` – Mazdak Jan 08 '16 at 18:37
  • @Kasramvd of course, who would have an unknown number of lists *not* in any collection? – timgeb Jan 08 '16 at 18:38
  • @timgeb This question is not clear, first of all we need to know that what OP means by unknown?? If it's unknown why we expect python knows that? :-) – Mazdak Jan 08 '16 at 18:44
  • @timgeb Thank you very much, your answer is just what I needed. Looks like the asterisk is the magic pill ! This is first time I pose question on this website, please let me know if there is a way I can give you some credits. – Zimo Yin Jan 08 '16 at 18:57
  • No problem happy coding. There's nothing you can or need to do. – timgeb Jan 08 '16 at 18:59

0 Answers0