1

Came across this example after lots of searching.

nested_lists = [[1, 2], [[3, 4], [5, 6], [[7, 8], [9, 10], [[11, [12, 13]]]]]]
flattened = lambda *n: (e for a in n for e in (flattened(*a) if isinstance(a, (tuple, list)) else (a,)))
print(list(flattened(nested_lists)))

It works but is ugly and hard to follow but I like that it was done in 1 line of code.

Is there a neater way while still keeping it as concise.

Thanks

To make ts clear the code should give the result [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

hulleyrob
  • 25
  • 6
  • 1
    sorry no dice, for the list I have given none of the highest rated examples that also use 1 line seem to work. By dont work they either leave some items in a list or return None. – hulleyrob Apr 19 '20 at 15:46
  • @Stidgeon--that answer only partially flattens so does not work on the posted list. It returns `[1, 2, [3, 4], [5, 6], [[7, 8], [9, 10], [[11, [12, 13]]]]]`. – DarrylG Apr 19 '20 at 15:47
  • Your solution is valid and compact. To make it easier to follow you could refactor it into a def-ed function with a yield statement. – Marcel Apr 19 '20 at 15:49
  • thanks @Marcel I should have been more clear in the original post. Im trying to come up with a 1 liner I can store away and use when needed in various scripts without having to resort to third party packages copy whole functions here and there. – hulleyrob Apr 19 '20 at 16:12

1 Answers1

0

Simple approach to flatten a nested list:

nested_lists = [[1, 2], [[3, 4], [5, 6], [[7, 8], [9, 10], [[11, [12, 13]]]]]]
output = []
def reemovNestings(l): 
    for i in l: 
        if type(i) == list: 
            reemovNestings(i) 
        else: 
            output.append(i)

# Driver code 
print ('The original list: ', nested_lists) 
reemovNestings(nested_lists) 
print ('The list after removing nesting: ', output)

Output:

The original list:  [[1, 2], [[3, 4], [5, 6], [[7, 8], [9, 10], [[11, [12, 13]]]]]]                                   
The list after removing nesting:  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
Sheri
  • 1,383
  • 3
  • 10
  • 26
  • thanks I was trying to write as little code as possible so I can just copy a paste a 1 liner into various scripts as needed. Currently using the one about but im sure there must be better 1 liners out there without resorting to 3rd Party packages. But yeah this solution actually flattens the given list unlike the ones in the "duplicate" questions. – hulleyrob Apr 19 '20 at 16:10