Transforming iterative statements into vector-based operations is known as vectorization. This approach is faster because modern CPUs are optimized for these types of operations.
list 1: [1, 2, 3, 4]
list 2: [4, 5, 6, 7]
one approach is to iterate through both lists and sum each corresponding element.
Without using ufuncs, we can utilize Python’s built-in zip() method:
x = [1, 2, 3, 4] y = [4, 5, 6, 7] z = [] for i, j in zip(x, y): z.append(i + j) print(z) |
With ufuncs, we can use the add() function:
import numpy as np x = [1, 2, 3, 4] y = [4, 5, 6, 7] z = np.add(x, y) print(z) |