What is the analogue of Haskell's zipWith function in Python?
zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
Python's zip() function creates an iterator that will aggregate elements from two or more iterables. You can use the resulting iterator to quickly and consistently solve common programming problems, like creating dictionaries.
The Python zip() function makes it easy to also zip more than two lists. This works exactly like you'd expect, meaning you just only need to pass in the lists as different arguments.
If multiple iterables are passed, zip() returns an iterator of tuples with each tuple having elements from all the iterables. Suppose, two iterables are passed to zip() ; one iterable containing three and other containing five elements. Then, the returned iterator will contain three tuples.
To zip multiple lists, you can just do zip(list1, list2, list3) , etc.
map()
map(operator.add, [1, 2, 3], [3, 2, 1])
Although a LC with zip()
is usually used.
[x + y for (x, y) in zip([1, 2, 3], [3, 2, 1])]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With