For Loop With Two Variables Python

For loop is used to iterate over list, dictionary, tuple , set and strings. In the current article we are going to learn about using two variables in a for loop.

Assuming you are already aware about a single variable for loop to iterate over sequence. Therefore going to cover a single param loop in a nutshell.

Single Param for loop example code:

employees = ["John", "Peter", "Joe", "Camren"]
for e in employees:
  print(e) 

Where Single variable e represents each value in list for each iteration and print employee name in above example.

Now Let’s come to the current topic about a for loop with two variables python.

Syntax

for a,b in sequence: 
 print(a,b) 

Note: Here sequence represents tuple, dictionary or multiple ranges aggregated using zip function as applicable. We will see in detail below with easy to understand examples.

There are multiple scenarios where we can use two different variables in for loop. Let’s go through one by one.

1. Loop through two lists simultaneously in python

Let’s execute the below example using the zip function in python to iterate two given lists at the same time.

import itertools 
students = ["John", "Alex", "Jo"]
books = ["Math", "Science"]

for s,b in zip(students, books): 
    print(s, b)

Output:

('John', 'Math')
('Alex', 'Science')

Explanation : Zip function here combining both lists and zipping them together :). It means Zip function aggregates given lists and returns a number of tuples depending on the shortest list length. Iteration will end once shortest list completed. For instance here we have two list

  • Students with three elements
  • Books with two elements

In the first iteration it will pick the first element from both lists and so it prints John from students and Math from books list. Same for the second iteration and will print Alex and Science.

But the Students list has three elements and books have only two elements therefore the it will stop iteration further because student third element Jo does not have mapping third value from books.

Also we can use the zip function for multiple lists as well. Let's see below example for three list.

import itertools 
students = ["John", "Alex", "Jo"]
books = ["Math", "Science"]
studentsId = [1]

for s,b,i in zip(students, books, studentsId): 
    print(s, b, i)

Output: ('John', 'Math', 1)

Explanation: We have added one more third list studentsId with one element only. Now we know how many times the loop with zip function iterates here?

Yes one time only due to one element in studentsId and therefore it stop executing further. Therefore the number of iterations for the for loop depends on the lowest list size.

2. How to increment two variables at once in python?

We can increase two params at the same time in a python loop. It depends on our requirements on how we want to achieve and what the expected result is.

Let’s see below example for demonstration purpose

Increment of two variables within for loop

firstCountNum = 0
secondCountNum = 0
print "-----------------------------------------------------------------------------"
for i,j in zip(range(2, 5), range(1, 5)): 
	firstCountNum += 2
	secondCountNum += 3
	print('i:', i, 'j:', j)
	print "First Count Num is ",firstCountNum
	print "Second Count Num is ",secondCountNum
	print "-----------------------------------------------------------------------------"
   

Output:

-----------------------------------------------------------------------------
('i:', 2, 'j:', 1)
First Count Num is  2
Second Count Num is  3
-----------------------------------------------------------------------------
('i:', 3, 'j:', 2)
First Count Num is  4
Second Count Num is  6
-----------------------------------------------------------------------------
('i:', 4, 'j:', 3)
First Count Num is  6
Second Count Num is  9
-----------------------------------------------------------------------------
    

Explanation : Loop through two params for loop using two sets of ranges. There are two kinds of parameters used here. Loop index params such as i & j. Another is count params firstCountNum & secondCountNum which get increased for each iteration by value 2 & 3 respectively.

Variable i & j is part of tuples created using the python built-in zip function. For loop iterate here three times as the number of matched tuples using both range values is three.

Another Variable firstCountNum & secondCountNum is assigned as 0 initially and gets incremented in each loop traversing.

Increment of two variables within for loop using function

def incrementMeBy2(value):
        return value+2

firstCountNum = secondCountNum = 0
print "-----------------------------------------------------------------------------"
for i,j in zip(range(2, 5), range(1, 5)): 
	print('i:', i, 'j:', j)
	firstCountNum = incrementMeBy2(firstCountNum)
	secondCountNum = incrementMeBy2(secondCountNum)
	print "First Count Num is ",firstCountNum
	print "Second Count Num is ",secondCountNum
	print "-----------------------------------------------------------------------------"
   

Explanation : Above code is designed for demonstration purpose for incrementing value using function where function incrementMeBy2 is used to increase passing number by 2. We can use the function approach for complex calculation and call inside the loop as shown in above example.