0

Consider a List that has a several nested list inside it.

['String example 1',
'String example 2',
['String example 3'],
['String example 4', 'String example 5'],
'String example 6']

The output should be

['String example 1',
'String example 2',
'String example 3',
'String example 4',
'String example 5',
'String example 6',]

I've use this code but the problem it also flatten a non nested string

flat_list = [num for sublist in text for num in sublist]
TripleBritz
  • 35
  • 1
  • 9

3 Answers3

1

Here's how you can do it. Check if the datatype of the item is a list or not. If it's not then append it directly. But if it's a list then append by looping through its items. :

flat_list = []
for sublist in text:
    if type(sublist) == list:
        for num in sublist:
            flat_list.append(num)
        
    else:
        flat_list.append(sublist)

Output:

['String example 1', 'String example 2', 'String example 3', 'String example 4', 'String example 5', 'String example 6']
Abhyuday Vaish
  • 2,357
  • 5
  • 11
  • 27
0

You can use isinstance(..., list) to check whether an item is a list, and then flatten the sublist:

lst = ['String example 1',
'String example 2',
['String example 3'],
['String example 4', 'String example 5'],
'String example 6']

def flatten(lst):
    for x in lst:
        if isinstance(x, list):
            yield from flatten(x)
        else:
            yield x

output = list(flatten(lst))
print(output)
# ['String example 1', 'String example 2', 'String example 3', 'String example 4', 'String example 5', 'String example 6']
j1-lee
  • 13,764
  • 3
  • 14
  • 26
0

I like @j1-lee 's answer, but using yield function (for recursion!) might be a bit confusing. Here is a more beginner-friendly version:

def flatten(lst):
    new_lst = []
    for x in lst:
        if isinstance(x, list):
            new_lst += flatten(x)
        else:
            new_lst.append(x)
    return new_lst
Aaron Lei
  • 96
  • 4