how to make one list from nested list 1

how to make one list from nested list

>>> from collections import Iterable
def flatten(lis):
     for item in lis:
         if isinstance(item, Iterable) and not isinstance(item, str):
             for x in flatten(item):
                 yield x
         else:        
             yield item

>>> lis = [1,[2,2,2],4]
>>> list(flatten(lis))
[1, 2, 2, 2, 4]
>>> list(flatten([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Here is what the above code is Doing:
1. The function flatten takes a list as input.
2. The function checks if the item is an iterable and not a string.
3. If the item is an iterable, then it calls the function flatten on the item.
4. If the item is not an iterable, then it yields the item.

Similar Posts