Online Tutorials & Training Materials | STechies.com
Register Login

Flatten List or Nested List Comprehension Python

28 Feb 2019 11:21 am || 0

List comprehensions are one of the most important features of Python. List comprehensions offer a smart way to create lists based on existing lists. Along with creating new lists, list comprehensions can be used for filtering and mapping elements of a list. Usually, list comprehensions have brackets and an expression, which is followed by a for loop. If statements are also used within these for loops.

List comprehensions always return a brand new list to the user.    

What is Nested List?

Nested list is nothing but a multiple list within a single list.

The loop way

Code:

# Python code to flatten the nested list
# Python 3 Code

# Input list
nested_lists = [[3, 4, 5],[ 7, 8, 9, 10]]

# Initialized empty flatten list 
flat_list = []

#flatten the list
for x in nested_lists:
        for y in x:
                flat_list.append(y)

# Final Output
print("Flatten List:",flat_list)

Output: 

Flatten List: [3, 4, 5, 7, 8, 9, 10]

Explanation

In this program, we can see an empty list and a nested list. The empty list called flat_list is populated with all the elements of the nested list, making it one-dimensional. This happens inside the for loop, where the inner loop iterates over the elements of the nested list and adds them to the empty list. This is done using the append() method. The append() method adds each element of the nested list to the end of the empty list.                  

List Comprehension Way

# Python code to flatten the nested list
# Python 3 Code

# Input list
nested_lists = [[3, 4, 5],[ 7, 8, 9, 10]]

#flatten the lists
flat_list = [y for x in nested_lists for y in x]
print("Flatten List: ",flat_list)

Output: 

Flatten List: [3, 4, 5, 7, 8, 9, 10]

Explanation

We can see that a for loop is used for adding all the elements of the nested list to the flat_list, that has no elements. This results in a one-dimensional list called flat_list havibg elements [3, 4, 5, 7, 8, 9, 10].  

itertools.chain() Function

# Python code to flatten the nested list
# Python 3 Code

# Input list
nested_lists = [[1,2,3],[4,5,6], [7], [8,9]]

import itertools
listflat = list(itertools.chain(*nested_lists))
print("Flatten List:",listflat)

Output: 

Flatten List: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Explanation

The nested_list variable is initialized with the elements [[1,2,3],[4,5,6], [7], [8,9]]. In the next line of code, the import statement is used for loading the module itertools. Then, the itertools.chain() method is used for flattening the list within the nested_list variable. The next line of code is:

listflat = list(itertools.chain(*nested_lists))

Here, the itertools.chain() method takes in the elements of the nested_lists as an argument. The * symbol before the nested_lists defines multiple or all its elements. Then the result of this method is fed to the list() method for converting the sequence into a list. The ultimate result of the list() method is assigned to a variable called listflat. The value within the listflat variable is printed out in the last line using the print() method.

The final result is:

Flatten List: [1, 2, 3, 4, 5, 6, 7, 8, 9]

tertools.chain.from_iterable()

# Python code to flattern the nested list
# Python 3 Code

# Input list
nested_lists = [[1,2,3],[4,5,6], [7], [8,9]]

import itertools
listflat = list(itertools.chain.from_iterable(nested_lists))
print("Flatten List:",listflat)

Output: 

Flatten List: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Explanation

In this program, a variable called nested_lists is assigned the value of [[1,2,3],[4,5,6], [7], [8,9]]. Then the itertools module is loaded using the import statement. The itertools.chain.from_iterable() method is used next. This method takes in a single argument which can be a list of lists. So, elements of the nested_lists are passed as an argument to the itertools.chain.from_iterable() method. The result of this function call is passed as the argument for the list() method which converts the sequence into a list.

The final flattened list is printed using the code print("Flatten List:",listflat). The resultant value of the listflat variable is [1, 2, 3, 4, 5, 6, 7, 8, 9].  

Conclusion

Along with custom methods and lists, list comprehension techniques can be used for file operations. You can filter elements from lists and also form strings. While creating lists, list comprehension techniques are faster and efficient than normal functions. However, to make the code more readable, avoid writing very long list comprehensions such as the ones involving for loops in a single line.