0

So I posted this question here.

permutations of lists python

And the solution works.. but i should have been more careful. Please take a look at the link above.

What if I dont have a lists explicitly as a,b,c,d but I have a list of lists.. something like

 lists.append(a)
  lists.append(b)

and so on. And in the end all i have is "lists"

This

for item in itertools.product(lists): 
   print(item)

doesnt work in this case??

Community
  • 1
  • 1
frazman
  • 32,081
  • 75
  • 184
  • 269

1 Answers1

2

Unpacking everything from a list using *:

>>> import itertools
>>> a = ["1"]
>>> b = ["0"]
>>> c = ["a","b","c"]
>>> d = ["d","e","f"]
>>> lists = [a,b,c,d]
>>> for item in itertools.product(*lists):
        print item


('1', '0', 'a', 'd')
('1', '0', 'a', 'e')
('1', '0', 'a', 'f')
('1', '0', 'b', 'd')
('1', '0', 'b', 'e')
('1', '0', 'b', 'f')
('1', '0', 'c', 'd')
('1', '0', 'c', 'e')
('1', '0', 'c', 'f')

This just unpacks the list into its elements so it is the same as calling itertools.product(a,b,c,d). If you don't do this the itertools.product interperets it as one item, which is a list of lists, [a,b,c,d] when you want to be finding the product of the four elements inside the list.

@sberry posted this useful link: http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists

jamylak
  • 128,818
  • 30
  • 231
  • 230
  • Hi. No. basically I want to have all the permutations of the element in a list (as posted in the link).. btw what is the difference between this method and something like a+b? just curious – frazman Apr 06 '12 at 06:44
  • Hi.. Great.. it works.. but what does the "*" does?? I think I just learnt somethign new in python :) – frazman Apr 06 '12 at 06:51
  • I wrote at the bottom what the `*` does. – jamylak Apr 06 '12 at 06:53