0

I want to write a function "product" which takes two lists a and b as parameters and returns a list with all pairs of elements from a and b as tuples. For example, I have a = ["a", "b"] and b = [1,2,3], and I want my output to be [("a", 1), ("a", 2), ("a", 3), ("b", 1), ("b", 2), ("b", 3)]. How do I do that? I have tried with

def product(a, b): 
    return list(map(lambda x, y:(x,y), a, b)) 

a = ["a", "b"] 
b = [1, 2, 3] 

print(product(a, b))

but I get only [('a', 1), ('b', 2)] as an output. What do I need to change? I don't really understand what I need to add. I am new to programming in python so It's kind of a hard challenge in the beginning, so any help would be appreciated!

  • FYI, `itertools.product` does this, but I'll assume you are trying to implement it yourself as practice. – chepner Feb 08 '20 at 01:11
  • Yeah I want to learn the basics, but how would you implement that into my problem? Going to look it up and read about it though! – PythonDaniel Feb 08 '20 at 01:13
  • You wouldn't integrate `itertools.product` into your function: it would *be* your function: `list(itertools.product(a, b))`. – chepner Feb 08 '20 at 01:22

2 Answers2

2

map operates over both lists in lockstep, similar to if you had written

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

To get all possible pairs, you need to iterate over both lists separately, in a nested fashion.

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

If you want to write this with nested maps (though I wouldn't recommend it), you'll want to use chain.from_iterable to flatten the result.

from itertools import chain
list(chain.from_iterable(map(lambda x: map(lambda y: (x,y), b), a)))
chepner
  • 497,756
  • 71
  • 530
  • 681
  • I think you made a typo in `[(x,y) for x in a for b in y]`. The `b in y` should be `y in b`. – RubenB Feb 08 '20 at 01:19
  • Yeah I was a bit confused at first, but now I get it, thanks a lot! I'm going to play around with a few more examples! – PythonDaniel Feb 08 '20 at 01:21
2

You could use list comprehension:

def product(a, b): 
    return [(a_, b_) for a_ in a for b_ in b]

a = ["a", "b"]
b = [1, 2, 3]

print(product(a, b))
RubenB
  • 525
  • 3
  • 10
  • Thanks a lot, this worked perfectly! Is this better than to use map and lambda? Or what is the benefits and drawbacks of them both? – PythonDaniel Feb 08 '20 at 01:19
  • @PythonDaniel See my answer for what a `map`-based solution would look like. List comprehensions are almost always clearer and generally preferred. – chepner Feb 08 '20 at 01:20
  • @chepner yes I saw it now, and maybe the list comprehension path is the one I should be trying to go with at first at least. – PythonDaniel Feb 08 '20 at 01:23