2

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!

1
  • All you need is numpy.hstack to flatten the list.
    – LevB
    Jun 17, 2020 at 17:36

1 Answer 1

2
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']
2
  • 1
    Great use of a generator! @Kush S. you can convert the result of extract to a list by doing list(extract(...)) Jun 17, 2020 at 16:31
  • What is the syntax to extract when the list is as such? [['Alexia', 60], ['Alissa', 30], ['Shane', 20], ['Grace', 24]]
    – Rosellx
    Mar 11, 2021 at 10:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.