Python Forum

Full Version: Problem in flattening list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
Go through this page
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]
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...ls.flatten
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.
Quote:See also collapse(), which can flatten multiple levels of nesting.