Flatten Nested List Iterator in Python

A nested list iterator flattens a multi-level list structure into a single sequence. Each element can be either an integer or another list containing integers or nested lists.

Problem Statement

Given a nested list like [[1, 1], 2, [1, 1]], we need to create an iterator that returns elements in flattened order: 1, 1, 2, 1, 1.

Algorithm

The solution uses recursion to flatten the nested structure during initialization ?

  • Initialize an empty result list and index counter

  • Recursively traverse the nested list using getVal()

  • If element is integer, add to result list

  • If element is list, recursively call getVal()

  • next() returns current element and increments index

  • hasNext() checks if more elements remain

Implementation

class NestedIterator:
    def __init__(self, nestedList):
        self.res = []
        self.index = 0
        self.getVal(nestedList)
    
    def getVal(self, nestedList):
        for item in nestedList:
            if isinstance(item, int):
                self.res.append(item)
            else:
                self.getVal(item)
    
    def next(self):
        self.index += 1
        return self.res[self.index - 1]
    
    def hasNext(self):
        return self.index < len(self.res)

# Test the iterator
nested_list = [[1, 1], 2, [1, 1]]
iterator = NestedIterator(nested_list)

print("Flattened elements:")
while iterator.hasNext():
    print(iterator.next())
Flattened elements:
1
1
2
1
1

How It Works

The iterator processes the nested structure in three phases ?

  1. Initialization: Recursively flattens the entire structure into self.res

  2. Iteration: next() returns elements sequentially from the flattened list

  3. Boundary Check: hasNext() prevents accessing beyond the list bounds

Example with Deeper Nesting

# Test with deeper nesting
complex_nested = [1, [4, [6, 7]], [8, 9]]
iterator = NestedIterator(complex_nested)

result = []
while iterator.hasNext():
    result.append(iterator.next())

print("Original:", complex_nested)
print("Flattened:", result)
Original: [1, [4, [6, 7]], [8, 9]]
Flattened: [1, 4, 6, 7, 8, 9]

Key Points

  • isinstance(item, int) checks if element is an integer

  • Recursive getVal() handles arbitrary nesting depth

  • All flattening happens during initialization for O(1) next() calls

  • Space complexity is O(n) where n is total number of integers

Conclusion

The nested list iterator uses recursive preprocessing to flatten complex nested structures. The hasNext() and next() methods then provide simple sequential access to the flattened elements.

Updated on: 2026-03-25T08:18:49+05:30

494 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements