How to iterate through a nested List in Python? (original) (raw)
Last Updated : 13 Dec, 2024
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.
Python `
a = [[1, 2], [3, 4], [5, 6]]
for sublist in a: for item in sublist: print(item)
`
Other methods that can use to iterate through a nested list are:
Table of Content
- Using Itertools.chain
- Using List Comprehension
- Using numpy.flatten()
- Using Recursive Function
- Using Stack (Iterative Approach)
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.
Python `
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
`
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.
Python `
a = [[1, 2], [3, 4], [5, 6]]
items = [item for sublist in a for item in sublist] print(items)
`
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.
Python `
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)
`
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.
Python `
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)
`
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.
Python `
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)
`
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 si 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 l 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: [GFGTABS] Python a = [1, 2, 3] a.ap 2 min read