Flatten List to Individual Elements using Python


Lists are a powerful data structure in Python that can hold many values of various types. We may come across nested lists where the items themselves are lists. In such circumstances, flattening the list and retrieving individual elements from the hierarchical structure may be essential. In Python, we have some built-in functions- chain(), extend(), and append() that can be used to solve the Flatten List to individual elements.

Let’s take an example of this:

Input

# Flatten List
my_list = [[11, 21, 31], [20, 30, 40], [4, 5, 6], [1, 2, 3]]

Output

# individual element in the list
[11, 21, 31, 20, 30, 40, 4, 5, 6, 1, 2, 3]

Syntax

The following syntax is used in all the examples-

itertools.chain()

The itertools is the module name that provides the chain () built-in function. This function takes several iterators as a parameter to return the single iterator.

extend()

The extend() is a built-in method in Python that adds the specific list element at the end of current list.

append()

The append() is a built-in method in Python that can add the element at the end of the list.

[[],[],[]]

The above representation state the nested list structure.

Using Nested loop

The program uses nested for loop to iterate into the sublist and using the append() method helps to

Example

In the following example, start the program by defining the function named flatten_list that accepts the parameter as lst( to receive the value of the input list). Then create the empty list in the variable flattened that will store the list containing individual elements. Next, use the nested for loop that iterates each sublist inside the list, and using append() it converts the sublist into an individual element. Then use the function return to get the new list. Now create the Flatten list in the variable nested_list and use the same variable as the parameter in the calling function to store it in the variable f_list. Finally, we are printing the result with the help of variable f_list.

def flatten_list(lst):
    flattened = []
    for sublist in lst:
        for item in sublist:
            flattened.append(item)
    return flattened

# Create the flattened list
nested_list = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]
# Calling function used in the variable
f_list = flatten_list(nested_list)
print("The individual element in the list:\n", f_list)

Output

 The individual element in the list:
 [10, 20, 30, 40, 50, 60, 70, 80, 90]

Using List Comprehension

The program uses list comprehension where the nested for loop is implemented to convert the Flatten List into individual elements.

Example

In the following example, begin the program by defining the function named flatten_list that accepts the parameter named lst which stores the values of the input list. Then return the function by using list comprehension where nested for loop iterate into the sublist. Next, create the flatten list and store it in the variable n_list. Then use the calling function in the variable f_list and use the same variable in the print function to get the result.

def flatten_list(lst):
    return [item for sublist in lst for item in sublist]

# Create the flatten list
n_list = [[11, 21, 31], [41, 51, 61], [71, 81, 91]]
# calling function used in the variable
f_list = flatten_list(n_list)
print("The individual element in the list:\n", f_list)

Output

 The individual element in the list:
 [11, 21, 31, 41, 51, 61, 71, 81, 91]

Using the itertools.chain() function

This is a Python program that uses the itertools module to flatten a nested list. The flatten_list function takes a nested list as an argument and returns a new list with all the elements from the sublists. The itertools.chain function combines all the sublists into one iterable, which is then converted into a list using the list function. The program then creates a nested list called nested_list, calls the flatten_list function with this list as an argument, and assigns the result to the variable flattened_list.

Example

In the following example, begin the program by importing the module named itertools which will help to convert the flattened list into individual elements. Then start creating the function flatten_list that accepts the parameter lst

import itertools
def flatten_list(lst):
    return list(itertools.chain(*lst))
# Create the flatten list
nested_list = [[12, 22, 32], [42, 52, 62], [72, 82, 92]]
# Calling function used in the variable
flattened_list = flatten_list(nested_list)
print("The individual element in the list:\n", flattened_list)

Output

 The individual element in the list:
 [12, 22, 32, 42, 52, 62, 72, 82, 92]

Using Recursion

The program uses the recursive function to work on flatten list and using the built-in function isintance() it will check the condition for object type and helps to generate the flattened list to individual elements.

Example

In the following example, the program flattens a constructed list iteratively by extracting every element. It then prints the flattened list that contains all of the individual elements from the nested list.

def flatten_list(lst):
    emp_list = []
    for item in lst:
        if isinstance(item, list):
            emp_list.extend(flatten_list(item))
        else:
            emp_list.append(item)
    return emp_list


# Create the flatten list
nested_list = [[81, 82, 83], [84, 85, 86], [87, 88, 89, 99, 100]]
f_list = flatten_list(nested_list)
print("The individual element in the list:\n", f_list)

Output

 The individual element in the list:
 [81, 82, 83, 84, 85, 86, 87, 88, 89, 99, 100]

Conclusion

We discussed the various method to solve the problem statement. We understood how flattening lists will provide us with an essential skill that will allow us to handle complex data structures more effectively and access individual elements. Also, knowing how to flatten lists will be useful whether we are working on data processing, algorithmic problem solving, or any other Python programming assignment or task.

Updated on: 16-Aug-2023

71 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements