user140259
user140259

Reputation: 480

Apply a function with lists like inputs

I want to create a new list (V) from other lists (a, b, c) and using a function, but I would like to take advantage of python and apply the function to the three lists and not element by element.

For example, I have the lists a, b and c; and the result after apply the function should be V. Thanks.

def mag(a, b, c):
    # something sophisticated
    return (a+b)*c

a = [1, 5, 7]
b = [4, 8, 3] 
c = [2, 6, 3]
V = [10, 78, 30]

Upvotes: 1

Views: 252

Answers (4)

keepAlive
keepAlive

Reputation: 6655

What about using only built-in functions? Like zip

>>> [mag(a_, b_, c_) for a_,b_,c_ in zip(a, b, c)]
[10, 78, 30]

Plus another python buit-in function, map which returns an iterator and thus makes things go faster and ends up saving memory:

>>> gen = map(lambda uple:mag(*uple), zip(a, b, c))
>>> list(gen)
[10, 78, 30]

Upvotes: 1

aydow
aydow

Reputation: 3801

An alternate solution is to use map and lambda

In [16]: list(map(lambda p: mag(*p), zip(a, b, c)))
Out[16]: [10, 78, 30]

Upvotes: 1

blhsing
blhsing

Reputation: 106553

You can easily do this with the map function:

V = list(map(mag, a, b, c))

Upvotes: 5

erip
erip

Reputation: 16935

You want to first zip the arguments, then map the function on the unpacked tuples:

from itertools import starmap

starmap(mag, zip(a,b,c))

See here for an example.

Upvotes: 3

Related Questions