Python | Ways to flatten a 2D list
Given a 2D list, write a Python program to convert the given list into a flattened list.
Method #1: Using chain.iterable()
# Python code to demonstrate # converting 2d list into 1d list # using chain.from_iterables # import chain from itertools import chain ini_list = [[1, 2, 3], [3, 6, 7], [7, 5, 4]] # printing initial list print ("initial list ", str(ini_list)) # converting 2d list into 1d # using chain.from_iterables flatten_list = list(chain.from_iterable(ini_list)) # printing flatten_list print ("final_result", str(flatten_list)) |
chevron_right
filter_none
Output:
initial list [[1, 2, 3], [3, 6, 7], [7, 5, 4]] final_result [1, 2, 3, 3, 6, 7, 7, 5, 4]
Method #2: Using list comprehension
# Python code to demonstrate # converting 2d list into 1d list # using list comprehension # import chain from itertools import chain ini_list = [[1, 2, 3], [3, 6, 7], [7, 5, 4]] # printing initial list print ("initial list ", str(ini_list)) # converting 2d list into 1d # using list comprehension flatten_list = [j for sub in ini_list for j in sub] # printing flatten_list print ("final_result", str(flatten_list)) |
chevron_right
filter_none
Output:
initial list [[1, 2, 3], [3, 6, 7], [7, 5, 4]] final_result [1, 2, 3, 3, 6, 7, 7, 5, 4]
Method #3: Using functools.reduce
# Python code to demonstrate # converting 2d list into 1d list # using functools.reduce # import functools from functools import reduce ini_list = [[1, 2, 3], [3, 6, 7], [7, 5, 4]] # printing initial list print ("initial list ", str(ini_list)) # converting 2d list into 1d # using functools.reduce flatten_list = reduce(lambda z, y :z + y, ini_list) # printing flatten_list print ("final_result", str(flatten_list)) |
chevron_right
filter_none
Output:
initial list [[1, 2, 3], [3, 6, 7], [7, 5, 4]] final_result [1, 2, 3, 3, 6, 7, 7, 5, 4]
Recommended Posts:
- Python | Sort Flatten list of list
- Python | Flatten given list of dictionaries
- Python | Ways to sum list of lists and return sum list
- Python | Ways to Spilt the list by some value
- Python | Ways to shuffle a list
- Different ways to clear a list in Python
- Extending a list in Python (5 different ways)
- Python | Ways to rotate a list
- Python | Ways to print list without quotes
- Python | Ways to find indices of value in list
- Python | Ways to remove duplicates from list
- Python | Ways to initialize list with alphabets
- Python | Ways to find length of list
- Python | Ways to create triplets from given list
- Python | Ways to format elements of given list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



