How to iterate through a nested List in Python?
A nested list is a list that contains other lists. Working with nested lists can seem tricky at first but it becomes easy once we understand how to iterate through them. This is the easiest way to loop through a nested list. We can use a for loop to access each sublist in the main list, and then use another for loop to access items within each sublist.
a = [[1, 2], [3, 4], [5, 6]]
for sublist in a:
for item in sublist:
print(item)
Output
1 2 3 4 5 6
Other methods that can use to iterate through a nested list are:
Table of Content
Using Itertools.chain
itertools.chain() is a method in Python that can combine multiple iterables (lists, tuples, etc.) into a single iterable. We can use it to flatten a nested list and then iterate over it.
import itertools
a = [[1, 2], [3, 4], [5, 6]]
# Flatten the nested list using itertools.chain
b = itertools.chain(*a)
print([i for i in b]) # b is a itertools object
Output
[1, 2, 3, 4, 5, 6]
Using List Comprehension
List comprehension is a compact way to create lists. It’s very useful for simple tasks. We can combine it with loops to access nested lists in a single line.
a = [[1, 2], [3, 4], [5, 6]]
items = [item for sublist in a for item in sublist]
print(items)
Output
[1, 2, 3, 4, 5, 6]
Using numpy.flatten()
If we are working with lists of numbers and want to convert a nested list into a flat list for easier iteration, numpy.flatten() can be useful. This method flattens multi-dimensional arrays into one long array.
import numpy as np
a = [[1, 2], [3, 4], [5, 6]]
# Convert the nested list to a numpy array and flatten it
b = np.array(a).flatten()
print(b)
Output
[1 2 3 4 5 6]
Using Recursive Function
For more complex nested lists (where the number of sublists may vary), we can use recursion. Recursion means that a function calls itself to solve smaller parts of the problem.
def iterate_nested_list(a):
for e in a:
# Check if the element is a list
if isinstance(e, list):
# Recur for inner list
iterate_nested_list(e)
else:
print(e, end=", ")
a = [[1, 2], [3, [4, 5]], 6]
iterate_nested_list(a)
Output
1, 2, 3, 4, 5, 6,
Using Stack (Iterative Approach)
If we want to avoid recursion and still handle deeply nested lists, we can use a stack. A stack is a data structure that stores elements in a way that the last element added is the first to be processed (Last In First Out or LIFO). We can push sublists onto the stack and process each one iteratively.
def iterate_with_stack(a):
# Start with the main nested list
stack = [a]
while stack:
# Take the last list from the stack
current = stack.pop()
for item in current:
# If it's a list, add it to the stack
if isinstance(item, list):
stack.append(item)
else:
print(item)
a = [[1, 2], [3, [4, 5]], 6]
iterate_with_stack(a)
Output
6 3 4 5 1 2