For Loop Over Two Lists in Python

Using a for loop over a list of values is as easy as looping through a variable, but if you want to learn how to loop over more than one list in Python, this article is for you. In this article, I’ll walk you through a tutorial on how to use a for loop over two lists in Python.

For Loop Over Two Lists in Python

A list is a data structure in Python that is a collection of values. Using a for loop over a list of values is as easy as looping over a single variable. For example, look at the code below:

In the code above, I am using a for loop first on a string variable and then on a list of values. 

Python can automatically loop through a list from start to finish. But if you want to use a for loop on two lists at the same time, you have to use an additional variable to move between the two lists. So here’s how to use a for loop over two lists in Python:

Output:
My Name is  Aman I am  22 years old
My Name is  Hritika I am  21 years old
My Name is  Akanksha I am  24 years old

In the code above, I created a list of names of people and their ages in another list. Then I introduced a new variable called “index” which is used to iterate through both lists to give output as the names of people with their ages. The last line (index = index + 1) updates the values of the index variable so that it can move through both the lists with each iteration of the for loop.

Also, Read – Python Projects with Source Code.

Summary

Python can automatically loop through a list from start to finish. But if you want to use a for loop on two lists at the same time, you have to use an additional variable to move between the two lists. I hope you liked this article on how to use a for loop over two lists in Python. Feel free to ask your valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1498

Leave a Reply