Python for with 2 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

Источник

For Loop with Two Variables (for i j in python)

Be on the Right Side of Change

The Python expression for i, j in XXX allows you to iterate over an iterable XXX of pairs of values. For example, to iterate over a list of tuples, this expression captures both tuple values in the loop variables i and j at once in each iteration.

for i, j in [('Alice', 18), ('Bob', 22)]: print(i, 'is', j, 'years old')
Alice is 18 years old Bob is 22 years old

Notice how the first loop iteration captures i=’Alice’ and j=18 , whereas the second loop iteration captures i=’Bob’ and j=22 .

for i j in enumerate python

The Python expression for i, j in enumerate(iterable) allows you to loop over an iterable using variable i as a counter (0, 1, 2, …) and variable j to capture the iterable elements.

Here’s an example where we assign the counter values i=0,1,2 to the three elements in lst :

lst = ['Alice', 'Bob', 'Carl'] for i, j in enumerate(lst): print(i, j)

Notice how the loop iteration capture:

🌍 Learn More: The enumerate() function in Python.

Python enumerate()

for i j in zip python

The Python expression for i, j in zip(iter_1, iter_2) allows you to align the values of two iterables iter_1 and iter_2 in an ordered manner and iterate over the pairs of elements. We capture the two elements at the same positions in variables i and j .

Here’s an example that zips together the two lists [1,2,3] and [9,8,7,6,5] .

for i, j in zip([1,2,3], [9,8,7,6,5]): print(i, j)

🌍 Learn More: The zip() function in Python.

for i j in list python

The Python expression for i, j in list allows you to iterate over a given list of pairs of elements (list of tuples or list of lists). In each iteration, this expression captures both pairs of elements at once in the loop variables i and j .

for i, j in [(1,9), (2,8), (3,7)]: print(i, j)

for i j k python

The Python expression for i, j, k in iterable allows you to iterate over a given list of triplets of elements (list of tuples or list of lists). In each iteration, this expression captures all three elements at once in the loop variables i and j .

for i, j, k in [(1,2,3), (4,5,6), (7,8,9)]: print(i, j, k)

for i j in a b python

Given two lists a and b , you can iterate over both lists at once by using the expression for i,j in zip(a,b) .

Given one list [‘a’, ‘b’] , you can use the expression for i,j in enumerate([‘a’, ‘b’]) to iterate over the pairs of (identifier, list element) tuples.

Summary

The Python for loop is a powerful method to iterate over multiple iterables at once, usually with the help of the zip() or enumerate() functions.

for i, j in zip(range(10), range(10)): # (0,0), (1,1), . (9,9)

If a list element is an iterable by itself, you can capture all iterable elements using a comma-separated list when defining the loop variables.

for i,j,k in [(1,2,3), (4,5,6)]: # Do Something

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

Be on the Right Side of Change 🚀

  • The world is changing exponentially. Disruptive technologies such as AI, crypto, and automation eliminate entire industries. 🤖
  • Do you feel uncertain and afraid of being replaced by machines, leaving you without money, purpose, or value? Fear not! There a way to not merely survive but thrive in this new world!
  • Finxter is here to help you stay ahead of the curve, so you can keep winning as paradigms shift.

Learning Resources 🧑‍💻

⭐ Boost your skills. Join our free email academy with daily emails teaching exponential with 1000+ tutorials on AI, data science, Python, freelancing, and Blockchain development!

Join the Finxter Academy and unlock access to premium courses 👑 to certify your skills in exponential technologies and programming.

New Finxter Tutorials:

Finxter Categories:

Источник

Читайте также:  Жадный алгоритм python пример
Оцените статью