0

Code is as follows:

def func(i,j):
    return i+j

m = list(product(range(5),range(7)))
print(m)
x = map(func,m)
list(x)

Error :

[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (3, 0), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6), (4, 0), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6)]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-181-fdda131ed5e8> in <module>()



      5 print(m)
      6 x = map(func,m)
----> 7 list(x)

TypeError: func() missing 1 required positional argument: 'j'

How to pass each pair in m through func. I don't want any for loop.

Cid
  • 13,273
  • 4
  • 22
  • 42
  • posible duplicate https://stackoverflow.com/questions/10834960/how-to-do-multiple-arguments-to-map-function-where-one-remains-the-same-in-pytho – Basalex Nov 29 '19 at 14:23

1 Answers1

2

You can use itertools.starmap:

from itertools import product, starmap

def func(i,j):
    return i+j

m = list(product(range(5),range(7)))
print(m)
x = starmap(func,m)
list(x)
jdehesa
  • 52,620
  • 6
  • 60
  • 94
  • Ahh... I'd forgotten about starmap... although `result = [func(*el) for el in m]` is readable enough – Jon Clements Nov 29 '19 at 14:25
  • @JonClements @chepner Yes, in most cases I probably wouldn't use `starmap` personally (I rarely use `map`), but I had the impression OP wanted something without a `for` (but maybe they just don't want proper loops but and are okay with comprehension/generator). – jdehesa Nov 29 '19 at 14:39
  • @chepner for 2-arg calls yeah... doesn't hurt to unpack it, but I'd probably not continue that pattern where there's more arguments... – Jon Clements Nov 29 '19 at 14:41
  • @chepner ... or there was a need to re-order or otherwise manipulate the arguments before passing to the function – Jon Clements Nov 29 '19 at 14:47