curious
curious

Reputation: 1554

How to call a function for every for iteration of a zip of two lists?

I have two lists: a=[1,2,3], b=[a,b,c]

I want for each zip of those two to call a function, but not to do it in a trivial way inside a for loop. Is there a pythonic way? I tried with a map:

map(func(i,v) for i,v in zip(a,b))

but it does not work

Upvotes: 0

Views: 47

Answers (3)

martineau
martineau

Reputation: 123473

If the function func doesn't return anything, you could use:

any(func(i, v) for i,v in zip(a, b))

Which will return False but not accumulate the results.

This would not be considered "Pythonic" by many since any() is being used for its side-effects, and therefore isn't very explicit.

Upvotes: 0

Alexander
Alexander

Reputation: 109546

A list comprehension is almost always faster or equivalent to map. If you append the results of the comprehension to a list (as in the example), then a comprehension is also faster than a for loop:

a = [1, 2, 3]
b = ['a', 'b', 'c']
c = []

def foo(x, y):
    global c
    result = x * y
    c.append(result)
    return result


>>> c
[]

>>> [foo(x, y) for x, y in zip(a, b)]
['a', 'bb', 'ccc']

>>> c
['a', 'bb', 'ccc']

Upvotes: 1

wim
wim

Reputation: 362786

The pythonic way is the for loop:

for i, v in zip(a, b):
    func(i, v)

Clear, concise, readable. What's not to like?

Upvotes: 5

Related Questions