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.
+2
A:
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']]
David Underhill
2010-02-07 20:41:17
is there a difference between xrange and range? and is it possible to do: for i in xrange(len(mylist),-1,-1): mylist[i:] + [newelement] + mylist[:i]because this is for homework and I never learned the way how you wrote it
Dan
2010-02-07 21:12:40
range generates each number in the sequence all at once and returns these numbers in a list.xrange generates each number in the range *as you need it*. Thus xrange uses less memory (a lot less if the sequence is quite large). So unless you really need all the numbers at once, xrange can be more efficient.The code you suggest would also do the trick. (Though you might want to do something with the lists you construct in the body of the for loop).
David Underhill
2010-02-07 22:56:37
A:
If l
is your list and X
is your value:
for i in range(len(l)+1):
l.insert(i, X)
print l
l.remove(X)
Dan Loewenherz
2010-02-07 20:45:04
A:
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')
Justin Peel
2010-02-07 21:23:11