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 Statement, Indentation and Comments
Python Program to Get the Last Element of the List
Python String isalpha()
Python Program to Solve Quadratic Equation
Python Global Keyword
Python Dictionary items()
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python Program to Catch Multiple Exceptions in One Line
Python reversed()
Python Program to Check Whether a String is Palindrome or Not
Python bool()
Python Anonymous / Lambda Function
Python tuple()
Python String casefold()
Python Program to Slice Lists
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python Generators
Python List
Python Matrices and NumPy Arrays
Python Program to Transpose a Matrix
Python del Statement
Python Program to Safely Create a Nested Directory
Python locals()
Python frozenset()
Python String upper()
Python Machine Learning - Sebastian Raschka
Python Set issuperset()
Python Program to Convert Celsius To Fahrenheit
Python Dictionary update()
Python Namespace and Scope
Python Program to Multiply Two Matrices
Python String ljust()