How to loop through multiple variables in Python?

In this post, I describe how you can iterate/loop through multipe (two or more) variables at the same time in Python.

Iterate/loop through multiple variable using the zip function

In this post, I describe how to use the zip function to iterate/loop through multiple variables at the same time in python. In the below example I defined three variables with the same length, however, the zip function can handle any number of input variables:

var1 = [1,2,3]
var2 = [4,5,6]
var3 = [7,8,9]
for v1,v2,v3 in zip(var1, var2, var3):
     print(v1, v2, v3)

Result:

1 4 7
2 5 8
3 6 9

The great thing about the zip function is that it can be used with arrays, lists, and dictionaries of different lengths. This is demonstrated in the below code snippet:

var1 = [1,2,3]
var2 = [4,5,6]
var3 = [7,8]
for v1,v2,v3 in zip(var1, var2, var3):
     print(v1, v2, v3)

Result:

1 4 7
2 5 8

Demonstration

The video below demonstrates the described code snippets above: