Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a value into all possible locations in a list

Tags:

python

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.

like image 287
Dan Avatar asked Feb 07 '10 20:02

Dan


People also ask

How do I add an item to a specific place in a list?

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.

How do you add an item to a specific place in a list Python?

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.

Which function inserts an object at given index in a list?

Python List insert() method inserts a given element at a given index in a list using Python.


3 Answers

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') 
like image 179
Justin Peel Avatar answered Oct 08 '22 23:10

Justin Peel


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']] 
like image 39
David Underhill Avatar answered Oct 09 '22 00:10

David Underhill


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]
like image 33
Janus Troelsen Avatar answered Oct 09 '22 00:10

Janus Troelsen