# Flatten Nested List Iterator in Python

PythonServer Side ProgrammingProgramming

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 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

Let us see the following implementation to get better understanding −

class NestedIterator(object):
def __init__(self, nestedList):
"""
:type nestedList: List[NestedInteger]
"""
self.res = []
self.index = 0
self.getVal(nestedList)
#print(self.res)
def getVal(self,NestedInteger):
for i in NestedInteger:
if(i.isInteger()):
self.res.append(i.getInteger())
else:
self.getVal(i.getList())
def next(self):
"""
:rtype: int
"""
self.index+=1
return self.res[self.index-1]
def hasNext(self):
"""
:rtype: bool
"""
if self.index == len(self.res):
return False
return True

## Input

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

## Output

[1,1,2,1,1]