Find Available Solution Here!

# For Loop With Two Variables Python

QuizCure Member Mar 19, 2023

For loop is used to iterate over the 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 of 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 it one by one.

## 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.

## 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.

## Iterate a list using itertools zip_longest in python. Explained with three-parameter.

In the previous examples, we learned how we can use the python zip function to loop through combinations of lists. For loop using zip function will execute depending on the size of lower size lists. It stops further execution code blocks once any of the zipped lists are exhausted.

Therefore to traverse all elements of the list we can use `itertools.zip_longest()`. It will traverse elements of the specified list until the longest lists are exhausted.

Syntax: itertools.zip_longest(*iterables, fillvalue=None)
• *iterables, number of iterables example iterable1, iterable2...
• Fillvalue: Default None if not provided

Let's explore with the following example python3 supported code for a better understanding

```import itertools

employee = ['Peter', 'Joe', 'Alex', 'Camren']
department = ['IT',  'Legal']
empId = [1001, 1002, 1004,  1006]

print ('Employee,', 'Department,', 'EmployeeID')
for (a, b, c) in itertools.zip_longest(employee, department, empId):
print (a, b, c)
```
```Result:
Employee, Department, EmployeeID
Peter IT 1001
Joe Legal 1002
Alex None 1004
Camren None 1006
```

Explanation:

• Imported itertools module to use Iterator zip_longest.
• Passed iterables as employee, department, empId contains elements as shown in the example.
• Fillvalue: Not given therefore yields a tuple with None as element value.
• Traversing three list elements with three params a,b,c
• The shortest list is a department, therefore, is filled with value None for corresponding index element
• Print retrieved values from the list in each iteration as result shown above.

### Using itertools.zip_longest with fillValue

```import itertools

employee = ['Peter', 'Joe', 'Alex', 'Camren']
department = ['IT',  'Legal']
empId = [1001, 1002, 1004,  1006]

print ('Employee,', 'Department,', 'EmployeeID')
for (a, b, c) in itertools.zip_longest(employee, department, empId, fillvalue='NA'):
print (a, b, c)
```
```Result:
Employee, Department, EmployeeID
Peter IT 1001
Joe Legal 1002
Alex NA 1004
Camren NA 1006
```

Added NA as filledvalue rather than default value None

## Practice Multiple-Choice Questions

• What will be the outcome for following for loop using zip function?
```for i, j in zip(range(1, 2), range(4, 2, -1)):
print(i,j)
```
Options are:
• What will be the result for following for loop with three params?
```for i, j, k in zip(range(5, 2, -2), range(4, 2, -1),  ['Peter', 'Joe', 'Alex', 'Camren']):
print(i,j, k)
```
Options are: