Example of an for loop in Python that loops multiple variables

  • 2021-07-18 08:34:28
  • OfStack

First, familiarize yourself with a function zip, and the following is the interpretation of zip using help (zip).

Help on built-in function zip in module __builtin__:

zip(...)

zip(seq1 [, seq2 [...]]) - > [(seq1[0], seq2[0] ...), (...)]

Return a list of tuples, where each tuple contains the i-th element
from each of the argument sequences. The returned list is truncated
in length to the length of the shortest argument sequence.

Look at an example:


x = [1, 2, 3]
y = [-1, -2, -3] # y = [i * -1 for i in x]
zip(x, y)

The results of zip are as follows:


 [(1, -1), (2, -2), (3, -3)]

zip ([seql,...]) takes a series of iterative objects as parameters, wraps the corresponding elements in the objects into individual tuple (tuples), and returns an list (list) made up of these tuples.

Get down to business: How to use an for loop to loop multiple variables at the same time? Use tuple. As follows, loop i and j variables at the same time.


for (i, j) in [(1, 2), (2, 3), (4, 5)]:
print(i, j)

The output is as follows:


(1, 2)
(2, 3)
(4, 5)

So if we want to add the elements in x and y separately, we can use the following code:


for (i, j) in zip(x, y):
  print(i + j)

Output:


0
0
0

Related articles: