Last Updated : 03 Jul, 2025
We are given a list that contains multiple sublists, and our task is to iterate over each of these sublists and access their elements. For example, if we have a list like this: [[1, 2], [3, 4], [5, 6]], then we need to loop through each sublist and access elements like 1, 2, 3, and so on.
Using Nested For LoopsThis is the most straightforward way to iterate through each sublist and access individual items.
Python
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for i in a:
for j in i:
print(j, end=' ')
print()
Explanation:
If our goal is to flatten a nested list into a single list, list comprehension offers a concise solution.
Python
a = [[1, 2], [3, 4], [5, 6]]
b = [i for j in a for i in j]
print(b)
[1, 2, 3, 4, 5, 6]
Explanation:
We can use enumerate() to track indices while iterating, which is helpful when we want to know the position of each sublist.
Python
a = [['Python', 'Java'], ['C++', 'C#'], ['Go', 'Rust']]
for i, g in enumerate(a, start=1):
print(f"Group {i}: {g}")
Group 1: ['Python', 'Java'] Group 2: ['C++', 'C#'] Group 3: ['Go', 'Rust']
Explanation:
itertools.chain() lets us combine multiple iterables into one. It's great for flattening nested lists efficiently, especially with large datasets, as it avoids creating extra lists in memory.
Python
from itertools import chain
a = [[1, 2], [3, 4], [5, 6]]
b = list(chain(*a))
print(b)
[1, 2, 3, 4, 5, 6]
Explanation:
Also read: matrices, list-comprehension, itertools.chain(), enumerate().
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4