Python Forum
Problem in flattening list - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Problem in flattening list (/thread-26465.html)



Problem in flattening list - Shahmadhur13 - May-02-2020

I tried to flatten list.I have nested list and i want all iterables of that nested list in one list without any nested list. Itried with itertool.chain and also with recursive function.

import itertools

a = [[1,2,3], [4,7,8],9]
b = list(itertools.chain(a))
print(b)
def flatten(list):
	a=[]
	for i in list:
		if type(i) == list:
			flatten(i)
		else:
			a.append(i)
	return a
	
b =  [[1,2,3], [4,7,8],9]
c = flatten(b)
print(c)
I still get nested list in result. No changes


RE: Problem in flattening list - pyzyx3qwerty - May-02-2020

Go through this page


RE: Problem in flattening list - bowlofred - May-02-2020

I'd probably do it this way.

a = [[1,2,3], [4,7,8],9]
l = []
for item in a:
    if isinstance(item, list):
        l.extend(item)
    else:
        l.append(item)
print(l)
Output:
[1, 2, 3, 4, 7, 8, 9]



RE: Problem in flattening list - DeaD_EyE - May-02-2020

It's good to know how to implement this without external dependencies.

Later you should take a look into more_itertools, after you now itertools.
https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.flatten


RE: Problem in flattening list - bowlofred - May-02-2020

I'd prefer to use a nice library, but the flatten in more-itertools unpacks all the elements in the list exactly one level. It won't cope with the 9 in the OP list.


RE: Problem in flattening list - DeaD_EyE - May-03-2020

Quote:See also collapse(), which can flatten multiple levels of nesting.