Udit Vashisht
Author: Udit Vashisht


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

  • 2 minutes read
  • 156 Views
Nested List to list - Python in just three lines of code

    Table of Contents

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

Set Passwords and Secret Keys in Environment Variables (Mac/Linux/Windows) - Python Quicktip
By Udit Vashisht

Hide Passwords and Secret Keys in Environment Variables

If you are into python , there is a fair chance that you would have contributed to open-source or had your code snippets/projects on Github or BitBucket.Some time your code involves some important credentials like passwords or secret keys ...

Read More
Difference between "==" and "is" in Python- Quick Tip
By Udit Vashisht

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
Python 3 useful tip-strip()-A useful built-in type.
By Udit Vashisht

Have you ever stumbled across a set of data that contains an extra underscore, character, or word as prefix or suffix, which you want to get rid of?

Python is known for having a resourceful standard library with lots of built-in types that can do a set of tasks in ...

Read More
Search
Tags
tech tutorials automate python beautifulsoup web scrapping webscrapping bs4 Strip Python3 programming Pythonanywhere free Online Hosting hindi til github today i learned Windows Installations Installation Learn Python in Hindi Python Tutorials Beginners macos installation guide linux SaralGyaan Saral Gyaan json in python JSON to CSV Convert json to csv python in hindi convert json csv in python remove background python mini projects background removal remove.bg tweepy Django Django tutorials Django for beginners Django Free tutorials Proxy Models User Models AbstractUser UserModel convert json to csv python json to csv python Variables Python cheats Quick tips == and is f string in python f-strings pep-498 formatting in python python f string smtplib python send email with attachment python send email automated emails python python send email gmail automated email sending passwords secrets environment variables if name == main Matplotlib tutorial Matplotlib lists pandas Scatter Plot Time Series Data Live plots Matplotlib Subplots Matplotlib Candlesticks plots Tutorial Logging unittest testing python test Object Oriented Programming Python OOP Database Database Migration Python 3.8 Walrus Operator Data Analysis Pandas Dataframe Pandas Series Dataframe index pandas index python pandas tutorial python pandas python pandas dataframe python f-strings padding how to flatten a nested json nested json to csv json to csv python pandas Pandas Tutorial insert rows pandas pandas append list line charts line plots in python Django proxy user model django custom user model django user model matplotlib marker size pytplot legends scatter plot python pandas python virtual environment virtualenv venv python python venv virtual environment in python python decorators