Python Lists allow you to easily store and process data in one place. Sometimes you may need to work with multiple lists or a list of lists, and iterate over them sequentially. There are multiple ways to do this in Python. In this article, we will look at how to iterate over multiple lists sequentially in Python.
How to Iterate over Multiple Lists Sequentially in Python
Here are the different ways to iterate over multiple lists sequentially in python.
1. Using itertools
itertools is a very useful library to work with iterables like lists. Let us say you have the following lists
L1=[1,2,3] L2=[4,5,6] L3=[7,8,9]
Here is the code to easily iterate over these lists sequentially. We use itertools.chain function to quickly iterate over multiple lists in a sequential manner. This is the fastest and most recommended way to iterate over multiple lists one after the other.
>>> for i in itertools.chain(L1,L2,L3): print i 1 2 3 4 5 6 7 8 9
2. Loop Through List of Lists
Sometimes you may have a list of lists as shown below
L4 = [L1, L2, L3] print L4 [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
In such cases you can simply use a loop inside another to iterate through multiple lists
>>> for i in L4: for j in i: print j 1 2 3 4 5 6 7 8 9
You may also use itertools.chain function to do the same. This is useful if you have large number of lists, or lists with large number of items.
>>> for i in itertools.chain(L4): for j in i: print j 1 2 3 4 5 6 7 8 9
3. Using Star(*) Operator
If you use Python >3, you can also use star(*) operator to unpack lists in a compact manner as shown below.
L1=[1,2,3] L2=[4,5,6] L3=[7,8,9] for i in [*L1, *L2, *L3]: print(i)
Here is the output you will see.
1 2 3 4 5 6 7 8 9
In this article, we have learnt different ways to iterate through multiple lists sequentially, one after the other.