1

I have been going through the questions on iteration through lists of unequal lengths, like this one, but I have been unable to find one which addresses my exact requirements.

I have two lists of unequal lengths:

list_1 = ["dog", "cat"]
list_2 = ["girl", "boy", "man", "woman"]

if I want to iterate through the lists of different lengths, I can use itertools zip-longest function as follows

for pet, human in zip_longest(list_1, list_2):
    print(pet, human)

The output I get is as follows:

dog girl
cat boy
None man
None woman

Question: What would I do if I wanted the iterator to output the following:

dog girl
dog boy
dog man
dog woman
cat girl
cat boy
cat man
cat woman

That, is in the iteration, I want to "combine" each element of list_1 to each element of list_2. What would I do?

Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
john_mon
  • 487
  • 1
  • 3
  • 13
  • 2
    @wim Put another way, you having shut this down within seconds of my answering is having the effect of making me less willing to devote any more time here to help other people. The Python topic has over a million questions, so you *could* argue that every question has been touched on before and that StackOverflow should become a static FAQ. Personally, I think the OP's question had some distinctive characteristics but that thought will never prevail against a small army of aggressive question closers. So, now users won't get to hear from the author of *itertools.product()*. – Raymond Hettinger Nov 12 '20 at 23:25
  • 4
    @RaymondHettinger I’m sorry, but *this* question is definitely a duplicate. The basic questions have indeed already been answered, but you and I both know that Python is not static, nor is the larger ecosystem surrounding it. There will be more questions. – Martijn Pieters Nov 12 '20 at 23:39
  • 3
    @RaymondHettinger do hit me up on something other than comments here if you wanted to discuss the relative merits of post closures and such. This isn’t really the place for it :-/ – Martijn Pieters Nov 12 '20 at 23:41
  • 1
    @RaymondHettinger I'm sorry to hear that! Your time and your content on SO is greatly appreciated (even helped me personally on several occasions). But an excess of repeated answers is unhelpful for the site, energy is better spent elsewhere. If you think the closure is wrong, you can vote to re-open and explain why it's significantly different - my vote is not the final say in the matter. – wim Nov 13 '20 at 00:01

1 Answers1

3

The tool you are looking for is itertools.product():

>>> from itertools import product
>>> list_1 = ["dog", "cat"]
>>> list_2 = ["girl", "boy", "man", "woman"]
>>> for pet, human in product(list_1, list_2):
        print(pet, human)
        
dog girl
dog boy
dog man
dog woman
cat girl
cat boy
cat man
cat woman
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485