0

Consider the following example:

def fcn_a(x, y):
    return x + y


def fcn_b(x, y):
    return x * y


def fcn_c(x, y):
    return x / y


fcns = [fcn_a, fcn_b, fcn_c]


x = [1, 2, 3]
y = [10, 20, 30]

I need to apply the functions in fcns to each pair of elements in x and y in order. Something like this:

result = []
for i in range(len(fcns)):
    result.append(fcns[i](x[i], y[i]))

# result == [11, 40, 0.1]

How can I accomplish this using a list comprehension?

Jason Strimpel
  • 11,832
  • 19
  • 65
  • 95
  • 5
    Where's the double iteration? You only have one `for` loop, what's the expected output? I think you're describing `[fn(xi, yi) for fn, xi, yi in zip(fcns, x, y)]`. – jonrsharpe Apr 14 '20 at 08:25
  • Hey, that's exactly what I'm describing. Put it in an answer let's make it official. – Jason Strimpel Apr 14 '20 at 08:26
  • 1
    @JasonStrimpel that is what you should use, the comment with `zip`, but note, your loop is directly translatable into a list comprehension, `[fcns[i](x[i], y[i]) for i in range(len(fcns))]` ... list comprehensions are basically sugar for those exact sort of loops – juanpa.arrivillaga Apr 14 '20 at 08:34
  • by using the zip built-in function you will not have the same behavior as using the `for` loop from the question if `fcns` has more itesm than the length of x or y will hide the IndexError – kederrac Apr 14 '20 at 08:45
  • 1
    I didn't downvote, for the record, or meant to imply that you are dumb. I just thought it would be helpful to point out. It's pretty much a duplicate of [this](https://stackoverflow.com/questions/3848829/how-to-map-a-list-of-data-to-a-list-of-functions) and [this](https://stackoverflow.com/questions/34835951/what-does-list-comprehension-mean-how-does-it-work-and-how-can-i-use-it) – juanpa.arrivillaga Apr 14 '20 at 08:48

1 Answers1

0

you can use the built-in function enumerate with list comprehention:

result = [f(x[i], y[i]) for i, f in enumerate(fcns)]

output:

[11, 40, 0.1]
kederrac
  • 15,339
  • 4
  • 25
  • 45