![]() |
Zip Keyword in For loop - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Data Science (https://python-forum.io/forum-44.html) +--- Thread: Zip Keyword in For loop (/thread-13892.html) |
Zip Keyword in For loop - 6pathsMadara - Nov-05-2018 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. RE: Zip Keyword in For loop - ichabod801 - Nov-05-2018 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. RE: Zip Keyword in For loop - 6pathsMadara - Nov-05-2018 Cheers for the help, I now understand it. |