Home > Software engineering >  Python - merge items of a dynamic nested list in a single list
Python - merge items of a dynamic nested list in a single list

Time:05-08

I have a code which takes input of the users and creates a nested list.

List = [list 1, list2, list 3,.....]

The list 1, list 2, list 3 and so on are dynamic and can keep increasing or decreasing.

So far my code output is:

All_data = [[a,b],[c,d],[1,2],[3,4],.....]

The output that I want (for the dynamic nested list):

All_data = [a,b,c,d,1,2,3,4,......]

Can anyone suggest me a solution to solve this?

CodePudding user response:

You can use itertools.chain:

itertools.chain(*All_data)

Or:

itertools.chain.from_iterable(All_data)

This creates an iterator, if you want to get a list:

list(itertools.chain.from_iterable(All_data))

CodePudding user response:

Instead of creating a nested list, you could build a flat list from the beginning using list.extend. Then you can extend All_data as more lists come in:

All_data = []
for lst in List:
    All_data.extend(lst)

All_data.extend(some_other_list)

CodePudding user response:

You can use numpy.concatenate(). It will condense the nested list into a single list.

If your nested list is dynamic and can grow exponentially, then I will suggest to use itertools.chain.from_iterable() from itertools library. It will be faster because it will not convert the list into a numpy array like the first option.

  • Related