I want to flat a list that has nested and not nested elements. From this solution I've tried and it works if all elements within mylist
were lists, but
in mylist
I have simple text strings and nested lists.
My list is like this:
mylist = [
'tz',
'7',
['a', 'b', 'c'],
[['2'], ['4', 'r'], ['34']],
[['7'], ['3', ['2', ['1']]], ['9']],
[['11',['7','w']], 'U1', ['0']]
]
And my current code is this, getting the error below:
import collections#.abc
def flatten(l):
for el in l:
if isinstance(el, collections.Iterable) and not isinstance(el, (str, bytes)):
yield from flatten(el)
else:
yield el
mylist1=[list(flatten(sublist)) if type(sublist) is list else sublist for sublist in mylist]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
File "<stdin>", line 3, in flatten
TypeError: isinstance() arg 2 must be a type or tuple of types
>>>
My expected output would be like this
mylist1 = [
'tz',
'7',
['a', 'b', 'c'],
['2', '4', 'r','34'],
['7','3','2','1','9'],
['11','7','w','U1','0']
]
What is missing to fix this? thanks.
UPDATE
Now I'm getting this error with code suggested by @Alok
>>> for item in mylist:
... # if the item in mylist is a list, pass it to your flatten method else
... # add it to the final list
... if isinstance(item, list):
... final_list.append(list(flatten(item)))
... else:
... final_list.append(item)
...
Traceback (most recent call last):
File "<stdin>", line 5, in <module>
File "<stdin>", line 3, in flatten
TypeError: isinstance() arg 2 must be a type or tuple of types