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??

0

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

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
Hi.. Great.. it works.. but what does the "*" does?? I think I just learnt somethign new in python :)
I wrote at the bottom what the * does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.