d
WE ARE EXPERTS IN TECHNOLOGY

Let’s Work Together

n

StatusNeo

Python: N-Dimensional List to a 1-Dimension

The Problem

Nowadays lists are the most used data types in python, In most of the interviews, people ask questions about lists and how to convert n-dimensional lists to a single dimension. In this blog, we will see the solution to solve this problem using recursion and will try to get the solution in O(n) complexity.

The Solution

Recursion:

Recursion is a function calling itself again and again until or unless a specific condition is reached, in this blog we are going to use recursion only to get the single-dimension list.

Code:

  • First, we will create a function say converter that will receive an n-dimensional list and an empty list as an input. Example- def converter(input_list, output_list).
  • Now we will iterate through each element of the input element and will test for the type of the element.
  • If the type of the element is a list we will call the function again passing that element as an n-dimensional list.
  • Else we append that element in the empty list that was passed as an input during the calling of the function.
  • Finally, we will return that empty list
def converter(input_list, output_list):
    for elements in input_list:
        if type(elements) == list:
            converter(elements,output_list)
        else:
            output_list.append(elements)
    return output_list
    

Still Curious? Visit my website to know more!

For more interesting Blogs Visit- Utkarsh Shukla Author

Disrupting the Tech World: Product Owner at NerdyBio, Python Powerhouse, AWS Ace & Prolific Tech Blogger 💻💥

Add Comment