Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Problem in flattening list
#1
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
Reply
#2
Go through this page
pyzyx3qwerty
"The greatest glory in living lies not in never falling, but in rising every time we fall." - Nelson Mandela
Need help on the forum? Visit help @ python forum
For learning more and more about python, visit Python docs
Reply
#3
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]
Reply
#4
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
My code examples are always for Python >=3.6.0
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#5
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.
Reply
#6
Quote:See also collapse(), which can flatten multiple levels of nesting.
My code examples are always for Python >=3.6.0
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Flattening attribute access ruy 5 333 Jun-25-2021, 08:26 PM
Last Post: ruy
  flattening a list with some elements being lists Skaperen 17 3,280 Apr-09-2019, 07:08 AM
Last Post: perfringo
  Flattening List mp3909 8 2,911 Jan-26-2018, 12:13 AM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020