
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 −
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
- Related Articles
- Python program to Flatten Nested List to Tuple List
- Python Program to Flatten a Nested List using Recursion
- Flatten given list of dictionaries in Python
- Flatten Tuples List to String in Python
- How to flatten a shallow list in Python?
- Flatten tuple of List to tuple in Python
- Python - Ways to flatten a 2D list
- Nested list comprehension in python
- Python - Convert given list into nested list
- Python Program to Flatten a List without using Recursion
- Nested List Weight Sum II in Python
- Python - Convert List to custom overlapping nested list
- Convert a nested list into a flat list in Python
- Flatten a multilevel linked list in C++
- Find maximum length sub-list in a nested list in Python
