Run two loops simultaneously in python

In this article we shall see how to runs two loop simultaneously using python. This can be achieved by the zip() method.

Using the zip() method

In order to use the zip() function, first, we must know what this function does. According to the documentation,

The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.

We will be using two range function to generate numbers using loop. As per the definition the zip method we will passing the two range functions to the zip method. Let us look at this method with an example so that it will be easier to understand where I am going with this.

for num1, num2 in zip(range(0, 10), range(10, 20)):
    print(num1, num2)

The output of the above code is,

0 10
1 11
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9 19

Technically we are running the loop only once. But instead of running two loops separately and iterating from 0-9 in one loop and 10-19 in another loop we are combining it into a single loop.

We are replacing the below code with the above code.

for num1 in range(0, 10):
for num2 in range(10, 20):

I guess now you have a clear idea of what we are trying to do.


Hope this article is helpful. If you have any queries leave them in the comments below. I will try to answer as soon as possible.

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *