Iterate Over a List of Lists in Python (original) (raw)
Last Updated : 22 Apr, 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 Loops
This 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:
- **Outer loop iterates through each sublist.
- **Inner loop prints each item in the sublist.
- **end=' ' prints items on the same line, followed by print() for a new line per sublist.
Using List Comprehension
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 sub in n for i in sub]
print(b)
`
**Explanation:
- List comprehension flattens the nested list into a single list.
- ****"b"** contains all elements from "**a" in one dimension.
Using enumerate() on Nested Lists
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}")
`
Output
Group 1: ['Python', 'Java'] Group 2: ['C++', 'C#'] Group 3: ['Go', 'Rust']
**Explanation:
- **enumerate() tracks **index (i) of each sublist (group).
- **start=1 begins counting from 1.
- Useful when you need position info along with elements.
**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)
`
**Explanation:
- **chain(*a) unpacks and chains all sublists.
- Efficient and memory-friendly for large nested lists.
- Returns a flat list containing all elements.
Also read: **matrices, **list-comprehension, **itertools.chain(), **enumerate().
Similar Reads
- Python Lists In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s 6 min read
- Get a list as input from user in Python We often encounter a situation when we need to take a number/string as input from the user. In this article, we will see how to take a list as input from the user using Python.Get list as input Using split() MethodThe input() function can be combined with split() to accept multiple elements in a sin 3 min read
- Create List of Numbers with Given Range - Python The task of creating a list of numbers within a given range involves generating a sequence of integers that starts from a specified starting point and ends just before a given endpoint. For example, if the range is from 0 to 10, the resulting list would contain the numbers 0, 1, 2, 3, 4, 5, 6, 7, 8 3 min read
- Python - Add List Items Python lists are dynamic, which means we can add items to them anytime. In this guide, we'll look at some common ways to add single or multiple items to a list using built-in methods and operators with simple examples:Add a Single Item Using append()append() method adds one item to the end of the li 3 min read
- How to add Elements to a List in Python In Python, lists are dynamic which means that they allow further adding elements unlike many other languages. In this article, we are going to explore different methods to add elements in a list. For example, let's add an element in the list using append() method:Pythona = [1, 2, 3] a.append(4) prin 2 min read