Write a Python Program to Flatten a Nested List

Python Program to Flatten a Nested List

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn  Python programming concepts. You can learn Python language at your own speed and time. One can learn concepts of Python language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Write a Python Program to Flatten a Nested List

PROGRAM: Python Program to Flatten a Nested List

Python Program to Flatten a Nested List
Python Program to Flatten a Nested List
/* Python Program to Flatten a Nested List */
1: Using List Comprehension

my_list = [[1], [2, 3], [4, 5, 6, 7]]

flat_list = [num for sublist in my_list for num in sublist]
print(flat_list)

Output

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

2: Using Nested for Loops (non pythonic way)  

my_list = [[1], [2, 3], [4, 5, 6, 7]]

flat_list = []
for sublist in my_list:
for num in sublist:
flat_list.append(num)

print(flat_list)

Output

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

3: Using itertools package
import itertools

my_list = [[1], [2, 3], [4, 5, 6, 7]]

flat_list = list(itertools.chain(*my_list))
print(flat_list)

Output

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

4: Using sum()
my_list = [[1], [2, 3], [4, 5, 6, 7]]

flat_list = sum(my_list, [])
print(flat_list)

Output

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

5: Using lambda and reduce()
from functools import reduce

my_list = [[1], [2, 3], [4, 5, 6, 7]]
print(reduce(lambda x, y: x+y, my_list))

Output

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

 
 
 
 

Leave a Reply

Your email address will not be published. Required fields are marked *