Search code examples
pythonlistinsert

How to insert elements from one list to another generating all possible combinations


Hello guys I need some help with lists in python. Suppose I have two lists.

a = [3,1,5]
b = [2,4]

What I want is to insert the elements of the list b consecutively (without changing the order of a) generating new lists. For example.

ans = [[2,4,3,1,5],[2,3,4,1,5],[2,3,1,4,5],[2,3,1,5,4],[3,2,4,1,5]...]

Thaks for your help I hope I was able to express myself correctly.


Solution

  • Not the most clean way of doing this, but here's what I mean:

    from itertools import permutations
    
    a = [3,1,5]
    b = [2,4]
    
    def a_order_is_same(perm):
        i3, i1, i5 = perm.index(3), perm.index(1), perm.index(5)
        return i3 < i1 < i5
    
    ans = [p for p in permutations(a+b) if a_order_is_same(p)]
    
    for p in ans:
        print(p)
    
    --------------------------------------------------
    
    (3, 1, 5, 2, 4)
    (3, 1, 5, 4, 2)
    (3, 1, 2, 5, 4)
    (3, 1, 2, 4, 5)
    (3, 1, 4, 5, 2)
    (3, 1, 4, 2, 5)
    (3, 2, 1, 5, 4)
    (3, 2, 1, 4, 5)
    (3, 2, 4, 1, 5)
    (3, 4, 1, 5, 2)
    (3, 4, 1, 2, 5)
    (3, 4, 2, 1, 5)
    (2, 3, 1, 5, 4)
    (2, 3, 1, 4, 5)
    (2, 3, 4, 1, 5)
    (2, 4, 3, 1, 5)
    (4, 3, 1, 5, 2)
    (4, 3, 1, 2, 5)
    (4, 3, 2, 1, 5)
    (4, 2, 3, 1, 5)