0

Lets say that I have the following list.

strange_list = [3, 4, 5, [6, 7, 8, [9, 0, 9], 4, 34, 'hello'], [[[['wtf']]]]]

How do I get the following list, using some function in itertools module.

chain_strange_list = [3, 4, 5, 6, 7, 8, 9, 0, 9, 4, 34, 'hello', 'wtf']
Arman Mojaver
  • 352
  • 1
  • 9
  • Does this answer your question? [how to extract nested lists?](https://stackoverflow.com/questions/8327856/how-to-extract-nested-lists) – My Work May 13 '20 at 18:02
  • See [collapse](https://more-itertools.readthedocs.io/en/stable/api.html#combining) in more_itertools. – Chris Charley May 13 '20 at 18:04
  • This may help you https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists – nodarkside May 13 '20 at 18:09
  • I use `flatten = lambda *n: (e for a in n for e in (flatten(*a) if isinstance(a, (tuple, list)) else (a,)))` – dawg May 13 '20 at 18:14

2 Answers2

1

We can make a simple recursive function to deal with this without needing any imports.

def unpack(obj):
    if not isinstance(obj, list):
        yield obj
    else:
        for item in obj:
            yield from unpack(item)

list(unpack(strange_list))
>> [3, 4, 5, 6, 7, 8, 9, 0, 9, 4, 34, 'hello', 'wtf']

Keep in mind the base condition here is simple in that it checks if the current item in the iteration is a list. For more complex data types you would have to modify this condition to suit your needs.

gold_cy
  • 13,648
  • 3
  • 23
  • 45
0

What you're looking for is flattening of a list, you can check those: how to extract nested lists? Flatten list of lists How to make a flat list out of list of lists?

so following one of them and thanks to @Chris Charley for a tip:

from more_itertools import collapse
strange_list = [3, 4, 5, [6, 7, 8, [9, 0, 9], 4, 34, 'hello'], [[[['wtf']]]]]

list(collapse(strange_list))
# [3, 4, 5, 6, 7, 8, 9, 0, 9, 4, 34, 'hello', 'wtf']

My Work
  • 2,143
  • 2
  • 19
  • 47