3

I want to take a list, for instance List = [1,2,2], and generate its permutations. I can do this with:

NewList = [list(itertools.permutations(List))]

and the output is:

[[(1, 2, 2), (1, 2, 2), (2, 1, 2), (2, 2, 1), (2, 1, 2), (2, 2, 1)]]

The Problem: itertools.permutations returns a list of length 1 whose only entry is the list of all permutations of List. That is:

NewList[0] == [(1,2,2),(1,2,2),(2,1,2),(2,2,1),(2,1,2),(2,2,1)]

and

NewList[1] does not exist.

I want the output to be a list where each entry is one of the permutations. That is

NewList[0] == (1,2,2)
NewList[1] == (1,2,2)
NewList[2] == (2,1,2)
...
NewList[5] == (2,2,1)

The Question: Is there a command that will produce the permutations of List in this way? Failing that, is there a way to access the 'individual elements' of [list(itertools.permutations(List))] so I can do things with them?

1
  • Just remove the [] and the output you've posted is also incorrect, it should be : [[(1, 2, 2), (1, 2, 2), (2, 1, 2), (2, 2, 1), (2, 1, 2), (2, 2, 1)]] Commented Jul 31, 2013 at 14:38

2 Answers 2

4
>>> from itertools import permutations
>>> list(permutations([1,2,2]))
[(1, 2, 2), (1, 2, 2), (2, 1, 2), (2, 2, 1), (2, 1, 2), (2, 2, 1)]

You don't need to put it in a list again. i.e Don't do [list(permutations(...))] (By doing [] you are making a nested list and hence are unable to access the elements using testList[index], though you could do testList[0][index] but it would be better to just keep it as a list of tuples.)

>>> newList = list(permutations([1, 2, 2]))
>>> newList[0]
(1, 2, 2)
>>> newList[3]
(2, 2, 1)

Now you can access the elements by using their indices.

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

Comments

0

Why can't you do this:

NewList = [list(itertools.permutations(List))][0]

or even just this:

NewList = list(itertools.permutations(List))

By doing [ list(itertools.permutations(List)) ], you put the list of permutations (the one that you want) inside of another list. So the fix would be to remove the outer []'s

Comments

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.