For Loop with Two Variables in Python

For Loop With 2 Variables

Python is a high-level, general-purpose programming language. Python was created by Guido van Rossum and was first released on February 20, 1991. It is a widely used and easy language to learn. It has simplified syntax, which gives more emphasis on natural language. You can quickly write and execute the code in Python faster than in other languages.

Here we will learn about the for loop and how to loop through with the two variables. “for” loop is widely used and easy to implement. For loop is used to perform an iteration over the sequence.

Before diving into the topic, one should install Python in the system.

Check for Python Version

Python is already installed in the system. To check if it’s installed, open cmd/terminal and type python – -version

python --version
Python Version
Python Version

If you get the version then you are good to go. Else, you can refer here for the Python Installation. We need python in our system to run python codes.

What is a Loop?

Loops help you to execute a block of code repeatedly until the condition is met. There are three types of loops in python:

  • For Loop: It is used to iterate over a sequence like a list, tuple, set, dictionary, or string.
  • While Loop: It executes till the condition is True.
  • Nested Loop: Loops can be nested which means a loop inside the other loop’s body. For example: for loop inside a for loop, while loop inside the for loop, and so on.

You can refer to Python Loops for more details.

For Loop In Python

As we learned above a for loop is used to iterate over a sequence like a list, tuple, set, dictionary, or string. “for” is a reserved iteration keyword used for creating a “for” loop just like while.

Syntax of for loop:

for element in sequence:
    execute statement
  • for” is a keyword reserved for loop
  • element is a variable name of a single item during iteration.
  • in” is a reserved keyword used to check the value present in the sequence while the iteration
  • :” colon is the indication that now the body starts
  • then, the body of the for loop followed by 4 spaces(tab) for the indentation

Let’s look at the simple example of how the for loop works with one variable.

for” Loop with One Variable

Here is the for loop following the general syntax which is mentioned above. This is the most basic and easy example to understand how the loop runs through the list of languages.

languages = ["C", "Python", "Java", "JavaScript", "Go"]

for language in languages:
    print(language)
  • assigned a list of languages(C, Python, Java, JavaScript, Go) to the variable languages
  • as following the syntax started the loop with the keyword “for
  • language” is the arbitrary variable that represents a single element in the list of languages
  • “languages” is the list
  • lastly, we are printing the single element of the list one by one.

Output:

For Loop One Variable
For Loop One Variable

Now let’s move on to the topic we are here for which is looping through for loop using two variables.


for” Loop with Two Variables

Syntax changes a little bit here as we are using two variables as we have learned above.

for item1, item2 in sequence:
    execute statement

This syntax basically we can use over lists, and dictionaries else we might get errors. Let’s take a look in detail.

Example 1: Looping through Dictionary

A dictionary is used to store the data in the key: value pair. In the dictionary, we have items() method. It returns a list containing a tuple for each key-value pair. When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.

person = {"Dhushi": 6, "Lee": 32, "Marc": 30}

for key, value in person.items():
    print(f'Name: {key}, Age: {value}.')

In this piece of code, we have assigned the dictionary which contains key and value pairs to a person variable. We are looping through both keys and values, by using the items() function. Each repetition will provide you with both the key and value of each item.

Output:

For Loop Dictionary Two Variable
For Loop Dictionary Two Variable
  • 6 is the value of the Dhushi key
  • 32 is the value of the Lee key
  • 30 is the value of the Marc key

You may check: How to Initialize Dictionary in Python – A Step-By-Step Guide.

Example 2: “for” Loop using enumerate() function

enumerate() the function is used to retrieve the position index and corresponding value while looping through the list. Let’s take a look at the code.

Syntax:

enumerate(iterable, start=0)
languages = ['Python', 'C', 'Java', 'JavaScript']

for index, value in enumerate(languages):
    print(f'Index:{index}, Value:{value}')
  • In the languages variable, we are assigning a list of values
  • as following the syntax started the loop with the keyword “for
  • here we are using two arbitrary variable index and value

Output:

For Loop Enumerate Function
For Loop Enumerate Function

As an output, we are printing the index variable which contains the index value(starting from 0), and the value variable contains the values of the list.

Example 3: “for” Loop using zip() function

To loop over two or more sequences at the same time, the entries can be paired with the zip() function.

Syntax:

zip(*iterables, strict=False)
names = ['Dhushi', 'Praj', 'Lee']
languages = ['Python', 'JavaScript', 'Java']
for name, language in zip(names, languages):
    print('My name is {0}. My favourite language is {1}.'.format(name, language))
  • here we are looping through sequences which are lists stored in variable names and languages
  • as following the syntax started the loop with the keyword “for
  • the two variables used for the loops are name and language which will be storing the values of names and languages

Output:

For Loop Zip Function
For Loop Zip Function

In the output, we are getting the name from the first list and the language from the second list. Another way to think of zip() is that it turns rows into columns and columns into rows

Conclusion

In this article, we learned about the for loop and how to loop through using two variables. For loop is basically used for iterations to check certain conditions and execute it till it met the condition. For loop could be used with one arbitrary variable or even two as we have studied above. There are functions like enumerate(), and zip() which could be used with 2 variables for iteration.

You can refer to the Python Documentation for more information and learn about different topics.