OP keeps the order of list1, and masks it with elements from list2.
I create a powerset of list2, and extend it with Nones to match the length of list1 (= helper). Then I iterate over unique permutations of helper, masking one array with the other to hide parts of list1 where the mask contains a not-None value.
Powerset from: How to get all subsets of a set? (powerset)
from itertools import chain, combinations, permutations
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))
list1 = [1, 2, 3]
list2 = [4, 5]
solutions = []
for s in powerset(list2):
# for every possibility of list2
helper = [None] * (len(list1) - len(s))
helper.extend(s)
# create something like [None, None, 4]
for perm in set(permutations(helper, len(helper))):
# for each permutation of the helper, mask out nones
solution = []
for listchar, helperchar in zip(list1, perm):
if helperchar != None:
solution.append(helperchar)
else:
solution.append(listchar)
solutions.append(solution)
print(solutions)
# [[1, 2, 3], [4, 2, 3], [1, 4, 3], [1, 2, 4], [1, 2, 5], [5, 2, 3], [1, 5, 3], [1, 5, 4], [4, 2, 5], [5, 2, 4], [5, 4, 3], [1, 4, 5], [4, 5, 3]]