Flatten 2-D List

Given a 2-D list (a list of lists), write a Python program to flatten the 2-D list into a 1-D list.

Example 1:

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

Example 2:

Input: [[10,20,30],[40,50,60],[70,80,90]] 
Output: [10,20,30,40,50,60,70,80,90]

You can use nested for loops or list comprehension to flatten the list.

def flatten_list(nums):
    return [element for sublist in nums for element in sublist]

© Let’s Data Science


Unlock AI & Data Science treasures. Log in!