Flatten Nested List Iterator in Python


Suppose we have a nested list of integers; we have to implement an iterator to flatten it. Each element is either an integer, or a list. The elements of that list may also be integers or other lists. So if the input is like [[1, 1], 2, [1, 1]], then the output will be [1, 1, 2, 1, 1]

To solve this, we will follow these steps −

  • In the initializing section, it will take the nested list, this will work as follows −

  • set res as empty list, index := 0, call getVal(nestedList)

  • The getVal() will take nestedIntegers, this will work as −

  • for i in nestedIntegers

    • if i is an integer, then insert the i into res array, otherwise call getVal(the i list)

  • The next() method will return the value pointed by index, and increase index by 1

  • the hasNext() will return true, when there is an element next to it, otherwise false

Example(Python)

Let us see the following implementation to get a better understanding −

 Live Demo

class NestedIterator(object):
   def __init__(self, nestedList):
      self.res = []
      self.index = 0
      self.getVal(nestedList)
      #print(self.res)
   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):
      if self.index == len(self.res):
         return False
      return True
ob = NestedIterator([[1,1],2,[1,1]])
while ob.hasNext():
   print(ob.next())

Input

[[1,1],2,[1,1]]

Output

1
1
2
1
1

Updated on: 29-Apr-2020

330 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements