Udit Vashisht
Author: Udit Vashisht


Nested List to list - Python in just three lines of code

  • Sept. 3, 2019, 3:28 p.m.
  • 2 minutes read
  • 109 Views
Nested List to list - Python in just three lines of code

Nested list to list in Python

Nested list in python can be converted to a flat list in python in just three lines of code. Let us assume that you have a following nested list.

[1, 2, [3, 4, [5, 6]], 7, 8, [9, [10]]]

Now, the above list is a nested list with multiple levels and we want to convert it to list using Python :-

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Nested list to list - Python - The longer way

First of all, I will show you the longer way, without using any third-party module. To convert a nested list to flat list we will use the following code:-

flat_list = []

def flatten_list(input_list):

    for item in input_list:
        if type(item) == list:
            flatten_list(item)
        else:
            flat_list.append(item)
    return flat_list

print(flatten_list(nested_list))

# output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Nested list to list in just three lines of code

That was the longer way. Now we will use pandas’ flatten function from pandas.core.common to do the same in just three lines of code.

from pandas.core.common import flatten

nested_list = [1, 2, [3, 4, [5, 6]], 7, 8, [9, [10]]]

print(list(flatten(nested_list)))

# Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

If you have liked our tutorial, there are various ways to support us, the easiest is to share this post. You can also follow us on facebook, twitter and youtube.

In case of any query, you can leave the comment below.

You can support us through patreon



Related Posts

Python F String - The Ultimate Usage Guide
By Udit Vashisht | 2 months, 3 weeks ago

Python F String

Python’s F-String was added in Python 3.6.0 as PEP-498 – Literal String Interpolation. Before the introduction of Python f-string, there were other methods of formatting like %-formatting, str.format() or string.Template(). These methods have their advantages, but the major disadvantage is that they ...

Read More
Python Logging Module - A Primer
By Udit Vashisht | 1 month, 3 weeks ago

Logging in python

Logging is the module in the standard library of python. Logging is an important tool for a programmer or developer, as it gives more insights about the code and any errors in it. In this tutorial, we will learn all about the python logging module. ...

Read More
Difference between "==" and "is" in Python- Quick Tip
By Udit Vashisht | 2 months, 3 weeks ago

What is the difference between “==” and “is” variable in Python?

If you are new to python you must have seen programmers using “==” and “is”, sometimes even interchangeably. Prima-facie, they look similar and many times you will use any of them. But there is a big difference between them. ...

Read More
Search