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

Flatten List or Nested List Comprehension Python

|| 0

Flatten List or Nested List Comprehension Python
Stechies

List comprehensions is one of the most important features of Python. List comprehensions offer smart way to create lists based on existing lists.

What is Nested list?

Nested list is nothing but a multiple list within a single list.

The loop way

Code:

# Python code to flatten the nested list
# Python 3 Code

# Input list
nested_lists = [[3, 4, 5],[ 7, 8, 9, 10]]

# Initialized empty flatten list 
flat_list = []

#flatten the list
for x in nested_lists:
        for y in x:
                flat_list.append(y)

# Final Output
print("Flatten List:",flat_list)

Output: 

Flatten List: [3, 4, 5, 7, 8, 9, 10]

List Comprehension Way

# Python code to flatten the nested list
# Python 3 Code

# Input list
nested_lists = [[3, 4, 5],[ 7, 8, 9, 10]]

#flatten the lists
flat_list = [y for x in nested_lists for y in x]
print("Flatten List: ",flat_list)

Output: 

Flatten List: [3, 4, 5, 7, 8, 9, 10]

itertools.chain() Function

# Python code to flatten the nested list
# Python 3 Code

# Input list
nested_lists = [[1,2,3],[4,5,6], [7], [8,9]]

import itertools
listflat = list(itertools.chain(*nested_lists))
print("Flatten List:",listflat)

Output: 

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

tertools.chain.from_iterable()

# Python code to flattern the nested list
# Python 3 Code

# Input list
nested_lists = [[1,2,3],[4,5,6], [7], [8,9]]

import itertools
listflat = list(itertools.chain.from_iterable(nested_lists))
print("Flatten List:",listflat)

Output: 

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

 


Advertisement
Advertisement
Advertisement