Flattening a nested list in Python

Issue

I am facing some difficulty flattening parts of a nested list in Python.
Here is the list:

[['31', '1'], '32', ['8', '16'], ['1', '3', '12'], ['4', '12'], '32', ['1', '3', '12'], ['4', '12'], '32', ['30', '1', '1']]

I want to flatten any lists inside of that list with the end result looking like this:

['31', '1', '32', '8', '16', '1', '3', '12', '4', '12', '32', '1', '3', '12', '4', '12', '32', '30', '1', '1']

From looking up ways to do this I tried this code:

list1 = (list(itertools.chain.from_iterable(list1)))

However, it not only flattens the lists but also the individual strings, splitting any string with more than 1 character (i.e. ’32’ becomes ‘3’, ‘2’) looking like this:

['31', '1', '3', '2', '8', '16', '1', '3', '12', '4', '12', '3', '2', '1', '3', '12', '4', '12', '3', '2', '30', '1', '1']

Is there a way to flatten only the lists inside of this list and not the individual strings? Sorry if the terminology is incorrect, I am not too familiar with manipulating this kind of list. Thank you!

Solution

arr = [['31', '1'], '32', ['8', '16'], ['1', '3', '12'], ['4', '12'], '32', ['1', '3', '12'], ['4', '12'], '32', ['30', '1', '1']]

def extract(array):
    for item in array:
        if type(item) in [set, list, tuple]:
            yield from extract(item)
            continue
        yield item

print(list(extract(arr)))  # ['31', '1', '32', '8', '16', '1', '3', '12', '4', '12', '32', '1', '3', '12', '4', '12', '32', '30', '1', '1']

Answered By – Artyom Vancyan

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published