Posts

Showing posts with the label List Comprehensions

Element-wise Operation on Iterables

A simple example is to add two lists item-or-element-wisely, there are a few methods to achieve it, using map with operator.add or lambda, list comprehension or libraries like numpy. There are pros and cons, some are easier to expand to operate on more iterables like summation on elements over three lists, others are easier to change the operations like add elements from first two and subtract element from the third. The following is the benchmark of each method, ran with 3.4.5: With 10,000 elements, average time of 1,000 runs map with operator.add : list(map(add, X, Y)) = 1,746 us map with lambda : list(map(add, X, Y)) = 3,209 us map with sum and zip : list(map(sum, zip(X, Y))) = 2,853 us list comprehension with sum and zip: [sum(z) for z in zip(X, Y)] = 3,901 us list comprehension with + and zip : [x + y for x, y in zip(X, Y)] = 1,665 us numpy : X + Y ...