Online Tutorials & Training Materials | STechies.com
Register Login
Advertisement

Flatten or convert nested lists into a list in Python

|| 0

Flatten or convert nested lists into a list in Python
Stechies

In python sometimes we need to flatten a list of lists or flattering arrays. It is like writing a custom function to concatenate two arrays. The old way to do so using a couple of loops running inside the other and flatten it in one line using comprehension.

What is Nested list

Nested list a list which has multiple list in a single list.

The loop way

Example

#here is two list contents 4 and 7 total 11 contents after flatten
lof_lists = [range(4), range(7)]
flat_list = []
#flatten the list
for x in lof_lists:
for y in x:
flat_list.append(y)
print "contents:",flat_list

Output:

contents: [0, 1, 2, 3, 0, 1, 2, 3, 4, 5, 6]

List comprehension way

Example

#here is two list contents 4 and 7 total 11 contents after flatten
lof_lists = [range(4), range(7)]
#flatten the lists
flat_list = [y for x in lof_lists for y in x]
print "the contents list is ",flat_list

Output

The contents list is [0, 1, 2, 3, 0, 1, 2, 3, 4, 5, 6]

itertools.chain() Function

import itertools
listnested = [[1,2,3],[4,5,6], [7], [8,9]]
listflat = list(itertools.chain(*listnested))
print listflat

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9]

tertools.chain.from_iterable()

Works with Python >=2.6

import itertools
listnested = [[1,2,3],[4,5,6], [7], [8,9]]
listflat = list(itertools.chain.from_iterable(listnested))
print listflat

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

 


Advertisement
Advertisement
Advertisement