Inserting a value into all possible locations in a list
I am trying to do print all the possible outcomes of a given list and I was wondering how to put a value into various locations in the list. For example, if my list was [A, B]
, I want to insert X
into all possible index of the list such that it would return this [X, A, B]
, [A, X, B]
, [A, B, X]
.
I was thinking about using range(len())
and a for loop but not sure how to start.
Solution 1:
Use insert() to insert an element before a given position.
For instance, with
arr = ['A','B','C']
arr.insert(0,'D')
arr becomes ['D','A','B','C']
because D
is inserted before the element at index 0.
Now, for
arr = ['A','B','C']
arr.insert(4,'D')
arr becomes ['A','B','C','D']
because D
is inserted before the element at index 4 (which is 1 beyond the end of the array).
However, if you are looking to generate all permutations of an array, there are ways to do this already built into Python. The itertools package has a permutation generator.
Here's some example code:
import itertools
arr = ['A','B','C']
perms = itertools.permutations(arr)
for perm in perms:
print perm
will print out
('A', 'B', 'C')
('A', 'C', 'B')
('B', 'A', 'C')
('B', 'C', 'A')
('C', 'A', 'B')
('C', 'B', 'A')
Solution 2:
You could do this with the following list comprehension:
[mylist[i:] + [newelement] + mylist[:i] for i in xrange(len(mylist),-1,-1)]
With your example:
>>> mylist=['A','B']
>>> newelement='X'
>>> [mylist[i:] + [newelement] + mylist[:i] for i in xrange(len(mylist),-1,-1)]
[['X', 'A', 'B'], ['B', 'X', 'A'], ['A', 'B', 'X']]