Python : Convert list of lists or nested list to flat list

In this article we will discuss different ways to convert a list of lists or nested lists to a single flat list.

Convert a list of lists to a flat list

Suppose we have a list of lists i.e.

# List of list
listOfList = [ [1, 2, 3, 4, 5],
                [11, 22, 33, 44, 55],
                [17, 18, 19, 20, 21] ]

This list contains 3 different lists of integers. We want to convert this list of lists in to a single flat list, that should contain only integers like,

[1, 2, 3, 4, 5, 11, 22, 33, 44, 55, 17, 18, 19, 20, 21]

There are different ways to do this,

Use list comprehension to convert a list of lists to a flat list

We will use list comprehension to iterate over a lists of list and then for each internal list again iterate over the individual elements in that list. Then add those elements to a new list i.e.

# List of list
listOfList = [ [1, 2, 3, 4, 5],
                [11, 22, 33, 44, 55],
                [17, 18, 19, 20, 21] ]

# Use list comprehension to convert a list of lists to a flat list 
flatList = [ item for elem in listOfList for item in elem]

print('Flat List : ', flatList)        

Output:

Flat List :  [1, 2, 3, 4, 5, 11, 22, 33, 44, 55, 17, 18, 19, 20, 21]

Although this is a single line solution but this kind of coding is not easy to maintain. So, let’s see some other options too,

Use list.extend() to convert a list of lists to a flat list

In python list data type provides a method to add all the contents of an iterable to the existing list,

list.extend(iterable)

It extends the existing list object by appending all the contents of given iterable. Let’s use this to convert list of lists to a flat list,

# List of list
listOfList = [ [1, 2, 3, 4, 5],
                [11, 22, 33, 44, 55],
                [17, 18, 19, 20, 21] ]

flatList = []
for elem in listOfList:
    flatList.extend(elem)

print('Flat List : ', flatList)

Output:

Flat List :  [1, 2, 3, 4, 5, 11, 22, 33, 44, 55, 17, 18, 19, 20, 21]

How did it worked ?

We created a new empty list. Then using for loop we iterated over the list of lists and then for each internal list appended its individual elements to our new flat list using list.extend().

Well we achieved our result, but there is an another way to do this,

Use list.append() to convert a list of lists to a flat list

In python list data type provides a method to add an item at the end of a list,

list.append(x)

Let’s use this to convert list of lists to a flat list,

flatList = []
for elem in listOfList:
    for item in elem:
        flatList.append(item)

print('Flat List : ', flatList)            

Output:

Flat List :  [1, 2, 3, 4, 5, 11, 22, 33, 44, 55, 17, 18, 19, 20, 21]

How did it worked ?

We created a new empty list. Then using for loop we iterated over the list of lists, then for each internal list again iterated over the individual elements in that list. Then add those individual elements to a new list using list.append()

All the above solution will work in case of list of lists. But what if we have nested list like list of numbers & lists. Also, internal lists might contain more lists. How to create a flat list from this kind of nested list ?

How to convert a nested list to a flat list ?

Suppose we have a nested list that contain some number, some lists and these internal lists also contain some numbers & lists i.e.

# Nested list
nestedList = [
            [1, 2,3],
            [22,33], 1,3,4,
                [
                    [10,11],
                    [222,333, 
                        [88, 99]
                    ]
                ]
            ]

Now we want to convert this kind of nested list to a flat list like,

[1, 2, 3, 22, 33, 1, 3, 4, 10, 11, 222, 333, 88, 99]

To do that we have created a recursive function,

def flattenNestedList(nestedList):
    ''' Converts a nested list to a flat list '''
    flatList = []
    # Iterate over all the elements in given list
    for elem in nestedList:
        # Check if type of element is list
        if isinstance(elem, list):
            # Extend the flat list by adding contents of this element (list)
            flatList.extend(flattenNestedList(elem))
        else:
            # Append the elemengt to the list
            flatList.append(elem)    

    return flatList

It accepts a nested list as argument, then iterates over each element in that list. For each element it checks if its type is list or not.

  • If yes, then again calls the same function flattenNestedList() with this element (list) to get a flat list out of it. Then extends the main flat list with the returned flat list.
  • Whereas, if element is not a list then it adds that to the end of the list using list.append(),

Now let’s use this function to convert our nested list to a flat list i.e.

# Nested list
nestedList = [
            [1, 2,3],
            [22,33], 1,3,4,
                [
                    [10,11],
                    [222,333, 
                        [88, 99]
                    ]
                ]
            ]

# Convert a nested list to a flat list
flatList = flattenNestedList(nestedList)

print('Flat List : ', flatList)

Output:

Flat List :  [1, 2, 3, 22, 33, 1, 3, 4, 10, 11, 222, 333, 88, 99]

Complete example is as follows,

def flattenNestedList(nestedList):
    ''' Converts a nested list to a flat list '''
    flatList = []
    # Iterate over all the elements in given list
    for elem in nestedList:
        # Check if type of element is list
        if isinstance(elem, list):
            # Extend the flat list by adding contents of this element (list)
            flatList.extend(flattenNestedList(elem))
        else:
            # Append the elemengt to the list
            flatList.append(elem)    

    return flatList
 
def main():
 
    # List of list
    listOfList = [ [1, 2, 3, 4, 5],
                    [11, 22, 33, 44, 55],
                    [17, 18, 19, 20, 21] ]
 
    print('List of lists : ')
    print(listOfList)

    print('**** Convert a list of lists to a flat list ****')
    print('** Use List Comprehension to convert a list of lists to a flat list :')
   
    # Use list comprehension to convert a list of lists to a flat list 
    flatList = [ item for elem in listOfList for item in elem]

    print('Flat List : ', flatList)        
 
    print('** Use list.extend() to convert a list of lists to a flat list :')

    flatList = []
    for elem in listOfList:
        flatList.extend(elem)

    print('Flat List : ', flatList)            
 
    print('** Use list.append() to convert a list of lists to a flat list :')

    flatList = []
    for elem in listOfList:
        for item in elem:
            flatList.append(item)

    print('Flat List : ', flatList)            
    
    print('**** Convert a nested to a flat list ****')

    # Nested list
    nestedList = [
                [1, 2,3],
                [22,33], 1,3,4,
                    [
                        [10,11],
                        [222,333, 
                            [88, 99]
                        ]
                    ]
                ]

    print('Nested list :')
    print(nestedList)    

    # Convert a nested list to a flat list
    flatList = flattenNestedList(nestedList)

    print('Flat List : ', flatList)
 
 
if __name__ == '__main__':
    main()

Output:

List of lists : 
[[1, 2, 3, 4, 5], [11, 22, 33, 44, 55], [17, 18, 19, 20, 21]]        
**** Convert a list of lists to a flat list ****
PS E:\Study\Articles\Python> & C:/Users/varun/AppData/Local/Programs/Python/Python37/python.exe e:/Study/Articles/Python/List/flat_list.py
List of lists : 
[[1, 2, 3, 4, 5], [11, 22, 33, 44, 55], [17, 18, 19, 20, 21]]        
**** Convert a list of lists to a flat list ****
** Use List Comprehension to convert a list of lists to a flat list :
Flat List :  [1, 2, 3, 4, 5, 11, 22, 33, 44, 55, 17, 18, 19, 20, 21]
** Use list.extend() to convert a list of lists to a flat list :
Flat List :  [1, 2, 3, 4, 5, 11, 22, 33, 44, 55, 17, 18, 19, 20, 21]
** Use list.append() to convert a list of lists to a flat list :
Flat List :  [1, 2, 3, 4, 5, 11, 22, 33, 44, 55, 17, 18, 19, 20, 21]
**** Convert a nested to a flat list ****
Nested list :
[[1, 2, 3], [22, 33], 1, 3, 4, [[10, 11], [222, 333, [88, 99]]]]
Flat List :  [1, 2, 3, 22, 33, 1, 3, 4, 10, 11, 222, 333, 88, 99]

 

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top