. Advertisement .
..3..
. Advertisement .
..4..
A for loop is used to iterate across any sequence, such as a list, tuple, or dictionary. It can even loop across a string. Using Python, you may use different variables inside a for loop with lists and dictionaries, but not with a generic error.
Iterable unpacking refers to the simultaneous deployment of variables inside the same code line. This article will explain How to use a for loop for Multiple Variables in Python. Come check it out!
How to use a for Loop for Multiple Variables in Python?
To utilize a for loop, you may apply Zip in Python. Here is an example that can help you understand more: [“heeya,” “meet,” “jaydeep”]= students[95,98,88], students in zip for marks (students, marks): print(f”{marks} gets {students} marks”).
Output: Heeya receives a score of 95. Meet receives 98 points, while Jaydeep receives 88 points.
Another approach is: students = [“heeya”, “meet”, “jaydeep”] marks = [95,98,88] for i, student in enumerate(students): mark = marks[i] print(f”{student} gets {mark} marks”)
with the same Output: Heeya receives a score of 95. Meet receives 98 points, while Jaydeep receives 88 points.
The Methods
Method 1
You may utilize a for Loop with zip(). Let us understand more about this by using the following example.
students = ["heeya", "meet", "jaydeep"] marks = [95,98,88] for marks, students in zip(students, marks): print(f"{marks} gets {students} marks")
With Output:
heeya gets 95 marks
meet gets 98 marks
jaydeep gets 88 marks
Method 2
You may also utilize a for Loop on Multiple Variables by applying to enumerate(). Apply the following example to use it.
students = ["heeya", "meet", "jaydeep"] marks = [95,98,88] for i, student in enumerate(students): mark = marks[i] print(f"{student} gets {mark} marks")
With Output:
heeya gets 95 marks
meet gets 98 marks
jaydeep gets 88 marks
Conclusion
About the solution for How to use a for Loop for Multiple Variables in Python, you may either apply zip or apply to enumerate. We hope you find these approaches useful. Fill in the blanks with any questions or suggested responses to allow us to better support you.
Leave a comment