-1

I have a list/generator of arguments that I need to put into a function to apply it in a list. The thing is that I'm practicing functional programming and want to avoid the use of 'for loops' except inside liste comprehensions (or generators, dicts , etc).

I have a list of arguments and each argument corresponds to a unique element in a different list, and I have a function to work those arguments and I want it to return a list.

I'm already having trouble explaining it.

args = [a,b,c,...]
function = funct()
elements [cc,vv,dg,...] 

the function has to run with args[i] over elements[i] for each i (both lists have the same number of elements) but I don't need the combinations, just the one to one relation.

norman123123
  • 337
  • 2
  • 11

1 Answers1

1

Using zip:

You can use zip() to do what you want. From the documentation:

Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.

So to give an example:

>>> a = [1, 2, 3, 4]
>>> b = [2, 4, 6, 8]
>>> list(zip(a,b))
[(1, 2), (2, 4), (3, 6), (4, 8)]

As zip() returns an iterator, you can iterate over the tuples without the need for the list() call as in the example. This can be done in a list-comprehension where we unpack each tuple into the variables a and b and then pass these into your function funct() one by one:

[funct(a, b) for a, b in zip(args, elements)]
Joe Iddon
  • 18,600
  • 5
  • 29
  • 49