Python Forum
Zip Keyword in For loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Zip Keyword in For loop
#1
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.
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Cheers for the help, I now understand it.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020