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

I am a versatile professional who specializes in empowering businesses with digital solutions. With expertise in software engineering consulting, I provide valuable guidance and support to companies seeking to enhance their technological capabilities. Additionally, I excel as a host(Professionals Unplugged), author, poet, and photographer. This diverse skill set allows me to creatively express my thoughts and ideas through various mediums. As a host, I engage audiences and facilitate insightful conversations. As an author, my writings offer valuable insights and knowledge. As a poet, I capture emotions and experiences through the power of words. And as a photographer, I have a keen eye for capturing captivating visuals. Overall, my wide range of skills and experiences make me a valuable asset in the world of digital solutions and creative expression

Add Comment