- For Loop With Two Variables Python
- Scroll for More Useful Information and Relevant FAQs
- Loop through two lists simultaneously in python
- How to increment two variables at once in python?
- Increment of two variables within for loop
- Increment of two variables within for loop using function
- Iterate a list using itertools zip_longest in python. Explained with three-parameter.
- Using itertools.zip_longest with fillValue
- Was this post helpful?
- How to add two variables in Python
- How to add multiple variables in python
- How to add two string variables in Python
- How to combine two variables in python
- How to add two-variable using function
- How to add two numbers using class in Python
- Add int and string variables
For Loop With Two Variables Python
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.
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.
Scroll for More Useful Information and Relevant FAQs
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)
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
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 "-----------------------------------------------------------------------------"
----------------------------------------------------------------------------- ('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.
- *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
Was this post helpful?
Feedback (optional) Please provide additional details about the selection you chose above so that we can analyze the insightful comments and ideas and take the necessary steps for this topic. Thank you
How to add two variables in Python
Here, we can see how to add two variables in python.
- In this example, I have used the print statement to enter a variable.
- I have taken an input() to store the input value given by the user.
- The “+” operator is used to add the variables.
- The print(“The sum of variables “, variable) is used to get the output.
print("Enter var1") var1 = input() print("Enter var2") var2 = input() variable = int(var1)+int(var2) print("The sum of variables ", variable)
We can see the sum of variables is 7 as the output. You can refer to the below screenshot for the output.
This is how to add two variables in Python.
How to add multiple variables in python
Here, we can see how to add multiple variables in python.
- In this example, I have taken four variables like a,b,c,d.
- I have used the “+” operator to add multiple variables.
- I have used print(a + b + c + d) to get the output.
a = 2 b = 3 c = 7 d = 5 print(a + b + c + d)
We can see the sum of all the variables as the output. You can refer to the below screenshot for the output.
This code, we can use how to add multiple variables in Python.
How to add two string variables in Python
Now, we can see how to add two string variables in python.
- In this example, I have taken two strings as string1 and string2.
- string1 is assigned as a pen and string2 is assigned as a pencil.
- I have used the “+” operator to add the strings.
- I have used print(string) to get the output.
string1 = 'pen' string2 = 'pencil' string = string1 + string2 print(string)
The below screenshot shows the output.
This is the code, we can use to add two string variables in Python.
How to combine two variables in python
Here, we can see how to combine two variables in python.
- In this example, I have taken two variables as a and b.
- The variables a is assigned as a = “Welcome to” and the variable b is assigned as b = ” Pythonguides”.
- To combine the two variables, I have used the “+” operator.
- To get the output, I have used print(c).
a = "Welcome to" b = " Pythonguides" c = a + b print(c)
We can see both the strings are combined as the output. You can refer to the below screenshot for the output.
This is how to combine two variables in python.
How to add two-variable using function
Now, we can see how to add two-variable using function in python.
- In this example, I have defined a function as def add and passed the parameter as (a,b).
- The function is returned with the expression. The values to be added are called in the function.
- I have used print(add(5,20)) to get the output.
def add(a,b): return a + b print(add(5,20))
The sum of the two variables is the output. You can refer to the below screenshot for the output.
This is the code, how to add two-variable using function in Python.
How to add two numbers using class in Python
Here, we can see how to add two numbers using class in python.
- In this example, I have created a class using a constructor to initialize the value of the class
- I have created a method to add the numbers.
- I have taken two numbers as the input and created an object for the class to pass the parameter.
- The self is the keyword used to pass the attributes and methods to the class.
- To get the output, I have used print(“Result: “,obj.add()).
class cal(): def __init__(self,a,b): self.a=a self.b=b def add(self): return self.a+self.b a=int(input("Enter first number: ")) b=int(input("Enter second number: ")) obj=cal(a,b) print("Result: ",obj.add())
We can see the sum of numbers as the output. You can refer to the below screenshot for the output.
This code we can use to add two numbers using class in Python.
Add int and string variables
Here, we can see how to add int and string variables in Python.
- In this example, I have taken two variables as variable1 and variable2.
- The variable1 is assigned as ‘The number is ‘ and variable 2 is assigned as 5.
- To convert the int value to a string, I have used str(variable2).
- I have used print(variable1 + str(variable2)) to get the output.
variable1 = 'The number is ' variable2 = 5 print(variable1 + str(variable2))
You can refer to the below screenshot for the output.
This is how we can add int and string variable in Python.
In this Python tutorial, we have learned about Add two variables in python. Also, we covered these below topics:
- How to add two variables in python
- How to add multiple variables in python
- How to combine two variables in python
- How to add two string variables in python
- How to add two-variable using function
- How to add two numbers using class in python
- Append two variables in python
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.