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.
You can add an item to a list with the append() method. A new item is added at the end. If you want to add to other positions, such as the beginning, use the insert() method described later. A list is also added as one item, not combined.
The Python list data type has three methods for adding elements: append() - appends a single element to the list. extend() - appends elements of an iterable to the list. insert() - inserts a single item at a given position of the list.
Python List insert() method inserts a given element at a given index in a list using Python.
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')
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']]
If you want to insert a list into a list, you can do this:
>>> a = [1,2,3,4,5]
>>> for x in reversed(['a','b','c']): a.insert(2,x)
>>> a
[1, 2, 'a', 'b', 'c', 3, 4, 5]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With