0

I know that this doesn't have to be done by doing recursion. I want to combine two lists such as x = [0, 1] and y = ['a', 'b', 'c'] and create a function that puts them in a list of tuples such as: [(0, 'a'), (0, 'b'), (0, 'c'), (1, 'a'), (1, 'b'), (1, 'c')].

I know only how to do this for the first index of list x and struggling to figure out how to move on to further indexes. The output for the function below is: [(0, 'a'), (0, 'b'), (0, 'c')].

def combine(x, y, idx=0):
    if idx < len(y):
        return [(x[idx], y[idx])] + combine(x, y[1:])
    else:
        return []

I don't know how to get to get the list x to move onto further indexes. I think I may need to call all_pairs(list1, list2, index+1 instead of slicing the list. Do I need to have the function call itself twice? This may seem elementary but for whatever reason I can't figure it out.

Jeril
  • 7,858
  • 3
  • 52
  • 69
Gokira
  • 11
  • 2
  • 1
    Does this answer your question? [Cartesian product of two lists in python](https://stackoverflow.com/questions/52192855/cartesian-product-of-two-lists-in-python) – kaya3 Mar 04 '20 at 02:07
  • @kaya3 OP specifically asks for a *recursive* solution which none of the answers to that question are. – Nick Mar 04 '20 at 02:53
  • @Nick OP specifically says *"I know that this doesn't have to be done by doing recursion"* which seems to me to be the opposite to "this has to be done using recursion". – kaya3 Mar 04 '20 at 02:56
  • @kaya3 The question title asks for a recursive solution; the body just gives the message that OP understands that the problem can be solved using methods other than recursion. – Nick Mar 04 '20 at 02:57
  • @Nick I see your point. There are still other questions with recursive answers, e.g. [this one](https://stackoverflow.com/a/534085/12299000) and [this one](https://stackoverflow.com/a/17102114/12299000), although those are not specific to the case of two lists. – kaya3 Mar 04 '20 at 03:02
  • @kaya3 you're right, there's an answer there which is a recursive solution for lists – Nick Mar 04 '20 at 03:04
  • Does this answer your question? [Get the cartesian product of a series of lists?](https://stackoverflow.com/questions/533905/get-the-cartesian-product-of-a-series-of-lists) – Nick Mar 04 '20 at 03:04

1 Answers1

0

You can do as below

from itertools import product
a = list(product(x,y))
a

or just list comprehension as below

[(a,b) for a in x for b in y]

Output

[(0, 'a'), (0, 'b'), (0, 'c'), (1, 'a'), (1, 'b'), (1, 'c')]
moys
  • 7,747
  • 2
  • 11
  • 42