In this example, you will learn to iterate through two lists in parallel.
To understand this example, you should have the knowledge of the following Python programming topics:
- Python List
- Python zip()
- Python for Loop
1. Example 1: Using zip (Python 3+)
list_1 = [1, 2, 3, 4]
list_2 = ['a', 'b', 'c']
for i, j in zip(list_1, list_2):
print(i, j)
Output
1 a 2 b 3 c
Using zip() method, you can iterate through two lists parallel as shown above.
The loop runs until the shorter list stops (unless other conditions are passed).
2. Example 2: Using itertools (Python 2+)
import itertools
list_1 = [1, 2, 3, 4]
list_2 = ['a', 'b', 'c']
# loop until the short loop stops
for i,j in itertools.izip(list_1,list_2):
print i,j
print("\n")
# loop until the longer list stops
for i,j in itertools.izip_longest(list_1,list_2):
print i,j
Output
1 a 2 b 3 c 1 a 2 b 3 c 4 None
Using the izip() method of itertools module, you can iterate through two parallel lists at the same time. izip_longest() lets the loop run until the longest list stops.
Related posts:
Python Input, Output and Import
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python Program to Check Armstrong Number
Python Program to Get a Substring of a String
Python pass statement
Python String zfill()
Python dict()
Python Program to Illustrate Different Set Operations
Python Deep Learning Cookbook - Indra den Bakker
Python Variables, Constants and Literals
Python String strip()
Python dir()
Python Program to Find Factorial of Number Using Recursion
Python len()
Python String isdigit()
Python @property decorator
Python Program to Get Line Count of a File
Python Program to Find Armstrong Number in an Interval
Python Program to Find Hash of File
Python String upper()
Python Statement, Indentation and Comments
Python if...else Statement
Python Program to Display Fibonacci Sequence Using Recursion
Python eval()
Python locals()
Python Program to Find HCF or GCD
Python Set add()
Python RegEx
Python Machine Learning Eqution Reference - Sebastian Raschka
Python timestamp to datetime and vice-versa
Python String isprintable()
Python Program to Merge Mails