Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension equivalent to map on two lists in parallel [duplicate]

I understand that with one list argument map() can be replaced by a list comprehension. For example

map(lambda x : x**2, range(5))

can be replaced with

[x**2 for x in range(5)]

Now how would I do something similar for two parallel lists. In other words, I have a line of code with the following pattern:

map(func, xs, ys)

where func() takes two arguments.

How can I do the same thing with a list comprehension?

like image 311
Code-Apprentice Avatar asked Dec 25 '16 23:12

Code-Apprentice


People also ask

What is the list comprehension equivalent for list map?

6. What is the list comprehension equivalent for: list(map(lambda x:x**-1, [1, 2, 3]))? Explanation: The output of the function list(map(lambda x:x**-1, [1, 2, 3])) is [1.0, 0.5, 0.3333333333333333] and that of the list comprehension [x**-1 for x in [1, 2, 3]] is [1.0, 0.5, 0.3333333333333333].

Is map more efficient than list comprehension?

Map function is faster than list comprehension when the formula is already defined as a function earlier. So, that map function is used without lambda expression.

Can list comprehension return two lists?

The question was: 'is it possible to return two lists from a list comprehension? '. I answer that it is possible, but in my opinion is better to iterate with a loop and collect the results in two separate lists.


1 Answers

map() with multiple arguments is the equivalent of using the zip() function on those extra arguments. Use zip() in a list comprehension to do the same:

[func(x, y) for x, y in zip(xs, ys)]

Generally speaking, any map(func, a1, a2, .., an) expression can be transformed to a list comprehension with [func(*args) for args in zip(a1, a2, .., an)].

like image 200
Martijn Pieters Avatar answered Nov 09 '22 23:11

Martijn Pieters