Just for fun, a solution that:
- Allows inserting multiple values into all possible locations, not just one, and
- Minimizes temporaries
- Does not invoke
O(n * m)
work on the insertions (which naïve repeated calls to list.insert
would perform)
Bonus, (for the person who asked a duplicate question) it makes use of the itertools
module without it feeling completely forced:
import itertools
l1 = ['a','b','c','d','f']
l2 = ['Z', 'Y']
combined_indices = range(len(l1)+len(l2))
iterators = itertools.cycle(l1), itertools.cycle(l2)
l3 = []
for positions in map(frozenset, itertools.combinations(combined_indices , len(l2))):
l3.append([next(iterators[idx in positions]) for idx in combined_indices])
print(*l3, sep="\n")
Try it online!
which produces output of the form:
['Z', 'Y', 'a', 'b', 'c', 'd', 'f']
['Z', 'a', 'Y', 'b', 'c', 'd', 'f']
['Z', 'a', 'b', 'Y', 'c', 'd', 'f']
['Z', 'a', 'b', 'c', 'Y', 'd', 'f']
['Z', 'a', 'b', 'c', 'd', 'Y', 'f']
['Z', 'a', 'b', 'c', 'd', 'f', 'Y']
['a', 'Z', 'Y', 'b', 'c', 'd', 'f']
['a', 'Z', 'b', 'Y', 'c', 'd', 'f']
# ... eleven lines omitted ...
['a', 'b', 'c', 'd', 'Z', 'f', 'Y']
['a', 'b', 'c', 'd', 'f', 'Z', 'Y']
And for bonus fun, a version that inserts the elements of l2
in either order (and condenses the work to an absurdly complicated listcomp for funsies):
from itertools import cycle, permutations, repeat
l1 = ['a','b','c','d','f']
l2 = ['Z', 'Y']
combined_indices = range(len(l1)+len(l2))
i1next = cycle(l1).__next__
l3 = [[pos_to_l2[pos] if pos in pos_to_l2 else i1next() for pos in combined_indices]
for pos_to_l2 in map(dict, map(zip, permutations(combined_indices, len(l2)), repeat(l2)))]
print(*l3, sep="\n")
Try it online!
which behaves the same, but produces outputs where the elements of l2
are inserted in either order (when l2[0]
shifts right, the other elements of l2
are inserted before it before they continue inserting after it, as in the first solution, e.g. the output sequence:
...
['Z', 'a', 'b', 'c', 'd', 'f', 'Y']
['a', 'Z', 'Y', 'b', 'c', 'd', 'f']
...
expands to:
...
['Z', 'a', 'b', 'c', 'd', 'f', 'Y']
['Y', 'Z', 'a', 'b', 'c', 'd', 'f'] # New
['a', 'Z', 'Y', 'b', 'c', 'd', 'f']
...