Python Forum

Full Version: Zip Keyword in For loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
import numpy as np

a = np.array([1, 2])
b = np.array([2, 1])

dot = 0

for e, f in zip(a, b):
    dot = dot + e*f
print(dot)
So after running this the answer is 4, but I don't understand what
the zip keywords functionality is in this loop, in fact I don't understand
any of the loop, can somebody please explain.
Maybe a clearer example would help. Say you have a = [1, 2, 3] and b = [6, 5, 4]. Then list(zip(a, b)) would be [(1, 6), (2, 5), (3, 4)]. The zip function returns a tuple of the first item in each list passed to it, then a tuple of the second item in each list, then a tuple of the third item, and so on until one of the lists runs out of items. Using for e, f in the loop is tuple assignment, assigning each item in the tuples returned by zip to the respective variables on the left.

That makes dot in your example equal to 1 * 2 + 2 * 1.
Cheers for the help, I now understand it.