0

i tried to gradually interleave one list with another. i mean: starting from the lists

a0 = list(range(3))      # [0, 1, 2]
a1 = list(range(10, 13)) # [10, 11, 12]

i would like to be able to iterate over the combinations

[0, 1, 2]
[10, 1, 2]
[0, 11, 2]
[10, 11, 2]
[0, 1, 12]
[10, 1, 12]
[0, 11, 12]
[10, 11, 12]

where first no element of a0 is replaced by the corresponding element of a1, then one, then two and then all of them.

what i came up with so far i this:

a01 = list(zip(a0, a1))

for i in range(1<<len(a0)):
    print(list(item[(i >> j) & 1] for j, item in enumerate(a01)))

where i zip the lists together and use i as a flag that tells me from what list to select an element.

this seems quite inelegant. is there something more elegant? i feel that itertools provides something that could be used here but i could not figure out anything so far.


the suggestion in the duplicate applied here is:

from itertools import product

for item in product(*zip(a0, a1)):
    print(item)

this produces the desired results (in a different order).

to get the order correct meowgoesthedog suggests in the comments:

list(map(lambda x: tuple(reversed(x)), product(*reversed(list(zip(a0, a1))))))

this answers the question.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
  • take a look at `itertools.roundrobin()` it could maybe interest you. [Here](https://docs.python.org/3/library/itertools.html#itertools-recipes)'s a link to the recipe. – Nenri Apr 01 '19 at 08:12
  • You're right - `itertools` does provide what you want: it's called `itertools.product` and I'll refer you to a previous question :) – Karl Knechtel Apr 01 '19 at 08:21
  • Judging by the silence on this question, you more or less have the best/shortest way of doing this. Minor tweaks maybe. – cs95 Apr 01 '19 at 08:23
  • 1
    To add to your edit, a variant which produces the correct order: `list(map(lambda x: tuple(reversed(x)), product(*reversed(list(zip(a0, a1))))))` – not exactly pretty (or as impressive as your solution with bit math) :S – meowgoesthedog Apr 01 '19 at 09:05
  • @meowgoesthedog thanks! that is quite some python-fu! will update that in the 'answer' section of the question. if you want i can vote to reopen the question and you can post that as an answer (would delete it in the question then...) – hiro protagonist Apr 01 '19 at 09:07

0 Answers0