Problem in flattening list
 Problem in flattening list Shahmadhur13 Programmer named Tim Posts: 16 Threads: 3 Joined: Apr 2020 Reputation: May-02-2020, 03:52 PM 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 pyzyx3qwerty Minister of Silly Walks Posts: 356 Threads: 13 Joined: Mar 2020 Reputation: May-02-2020, 03:57 PM 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 bowlofred Da Bishop Posts: 1,192 Threads: 3 Joined: Mar 2020 Reputation: May-02-2020, 04:03 PM 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 DeaD_EyE Da Bishop Posts: 1,640 Threads: 6 Joined: May 2017 Reputation: May-02-2020, 10:31 PM 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 bowlofred Da Bishop Posts: 1,192 Threads: 3 Joined: Mar 2020 Reputation: May-02-2020, 11:40 PM 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 DeaD_EyE Da Bishop Posts: 1,640 Threads: 6 Joined: May 2017 Reputation: May-03-2020, 12:40 AM 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 337 Jun-25-2021, 08:26 PM Last Post: ruy flattening a list with some elements being lists Skaperen 17 3,308 Apr-09-2019, 07:08 AM Last Post: perfringo Flattening List mp3909 8 2,919 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