Merging nested lists in Python


Nesting lists in Python refers to multiple lists within one another that can be useful when performing data manipulation tasks; however, occasionally we may wish to change or flatten this nested structure by "flattening a list", in Python terminology meaning changing from multiple hierarchical structures into one single (non-nested) structure where all elements belong under equal scope without hierarchy or hierarchies present. In this article, we will illustrate how to merge nested lists in python using different approaches.

Merging Nested Lists in Python Using Recursion Method

Code Explanation and Design Steps −

  • Step 1Import required module: we import an ‘Iterable’ class from ‘collections.abc’ module -iterable being one of Python's built-in interfaces that represent objects capable of returning its members one at a time.

  • Step 2Define a function to flatten lists: The flatten function takes one argument lst containing the list to be flattened; this function will then be called repeatedly on collections with any depth.

  • Step 3Iterate through each item in the list: ‘for’ loop iterates over each element in an input list, with the item being used as an index variable to represent which element currently dominates.

  • Step 4 − Determine an item is iterable but not String or Bytes.

  • Step 5 − Define a Nested List: This will be the list to be flattened.

  • Step 6 − Call Flatten Function and Print Output.

Note − This condition is key because strings and bytes can also be considered iterables; however, we don't wish to treat them that way since this would result in breaking string characters into individual letters. When an item meets this criterion but doesn't belong in either string or byte form we recursively call flatten to yield each element from this callout with yield from a statement in between calls of flatten function on said item.

It could potentially yield every element from each subsequent callout cycle yield from statement will return each element from these recursive calls yield from statement which will yield each element from this callback cycle with yield from statement between calls which elements from these calls will eventually yield each element from that callout loop recursively called by flatten function on its object itself. If an iterable item, string, or bytes does not match an iterable one, yield it: In this scenario, we use our else clause and simply return what it contains as it is.

Example 1

Code Execution and Implementation −

from collections.abc import Iterable
# Importing the Iterable class from the collections.abc module.

def flatten(lst):
   # Defining a function named 'flatten' that takes a list as input.
    
   for item in lst:

      if isinstance(item, Iterable) and not isinstance(item, (str, bytes)):
         
         yield from flatten(item)
      else:
         yield item
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# A nested list to be flattened.
print(list(flatten(nested_list)))

Output

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

Merging Nested Lists in Python Using List Comprehension Method

Code Explanation and Design Steps −

  • Step 1 − Open Jupyter Notebook in Anaconda prompt and start writing the code in its cell.

  • Step 2 − Creation of a function named flatten() a list contains one argument called nested_list.

  • Step 3 − Utilize list comprehension to create a list

  • Step 4 − A nested list needs to be defined first and then altered according to your individual needs and desires.

  • Step 5 − We run the ‘flatten()’ function against our original nested list and print its result, an orderly list consisting of elements extracted from said original list in their order of appearance should appear when printing with "print statement: All elements from Original Nested List..." as their order was originally defined.

Example 2

Code Execution and Implementation −

def flatten(nested_list):
   return [item for sublist in nested_list for item in sublist]
nested_list = [[1,2,3], [4,5,6], [7,8,9]]
print(flatten(nested_list))

Output

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

Note − This method only works for lists with one level of nesting. If additional lists contain further nests, this approach would fail to completely flatten them - in such a scenario a recursive solution like that shown above may be more appropriate.

Conclusion

In this article, we are merging nested lists in Python using two different methods such as recursion and list Comprehension methods. Both methods may be applied when flattening a nested list; the most appropriate choice will depend on your particular use case's level of nesting. Flattening a nested list in Python refers to the process of turning an array of sublists into an unordered one-dimensional list without sub-lists - an invaluable skill in data manipulation tasks that involve manipulating complex or unnecessary hierarchies of lists. It is particularly effective at simplifying operations that would otherwise involve extensive lists like these nested sublists.

Updated on: 18-Oct-2023

145 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements