logo-StatusNeo
d

WE ARE EXPERTS IN TECHNOLOGY

Let’s Work Together

Image Alt

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
    

References-

An optimistic Engineer passionate about technology, science, astrology, and photography. Visit this to know more- https://utkarshshukla.herokuapp.com/

Add Comment