Tutorialspoint
Problem
Solution
Submissions

Flatten a Nested List

Certification: Intermediate Level Accuracy: 100% Submissions: 5 Points: 10

Write a Python function to flatten a nested list of integers into a single list.

Example 1
  • Input: nested_list = [[1, 2], [3, [4, 5]], 6]
  • Output: [1, 2, 3, 4, 5, 6]
  • Explanation:
    • Step 1: Start with an empty result list.
    • Step 2: Process [1, 2]: Add 1 and 2 to the result list. Result = [1, 2].
    • Step 3: Process [3, [4, 5]]: Add 3 to the result list. Result = [1, 2, 3].
    • Step 4: Process [4, 5]: Add 4 and 5 to the result list. Result = [1, 2, 3, 4, 5].
    • Step 5: Process 6: Add 6 to the result list. Result = [1, 2, 3, 4, 5, 6].
    • Step 6: Return the flattened list [1, 2, 3, 4, 5, 6].
Example 2
  • Input: nested_list = [[1], [2, [3, [4]]]]
  • Output: [1, 2, 3, 4]
  • Explanation:
    • Step 1: Start with an empty result list.
    • Step 2: Process [1]: Add 1 to the result list. Result = [1].
    • Step 3: Process [2, [3, [4]]]: Add 2 to the result list. Result = [1, 2].
    • Step 4: Process [3, [4]]: Add 3 to the result list. Result = [1, 2, 3].
    • Step 5: Process [4]: Add 4 to the result list. Result = [1, 2, 3, 4].
    • Step 6: Return the flattened list [1, 2, 3, 4].
Constraints
  • 1 <= len(nested_list) <= 1000
  • Time Complexity: O(n) where n is the total number of elements in the nested list
  • Space Complexity: O(n)
ListRecursionCapgeminiDropbox
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use recursion to handle nested lists.
  • Iterate through each element, and if it is a list, recursively flatten it.
  • Append non-list elements directly to the result.

Steps to solve by this approach:

 Step 1: Initialize an empty list to store flattened elements
 
 Step 2: Iterate through each item in the input nested list  
 Step 3: Check if the current item is itself a list using isinstance()  
 Step 4: If the item is a list, recursively call flatten_list on it  
 Step 5: Add (extend) the flattened results to the output list  
 Step 6: If the item is not a list, simply append it to the output list  
 Step 7: Return the fully flattened list after processing all elements

Submitted Code :