Python | Merging nested lists

Python | Merging nested lists

Merging nested lists, commonly known as flattening, is the process of converting a list of lists (or deeper nested lists) into a single list without any nested elements.

Example:

Given:

nested_list = [[1, 2], [3, 4], [5, 6]] 

Desired output:

[1, 2, 3, 4, 5, 6] 

In this tutorial, we'll cover different approaches to flatten nested lists:

  • Using a loop: This is a straightforward way of extracting each element from sublists.
nested_list = [[1, 2], [3, 4], [5, 6]] flattened = [] for sublist in nested_list: for item in sublist: flattened.append(item) print(flattened) 
  • Using list comprehension: A concise way to flatten lists.
nested_list = [[1, 2], [3, 4], [5, 6]] flattened = [item for sublist in nested_list for item in sublist] print(flattened) 
  • Using itertools.chain: itertools.chain can be used to flatten a list of lists.
import itertools nested_list = [[1, 2], [3, 4], [5, 6]] flattened = list(itertools.chain.from_iterable(nested_list)) print(flattened) 
  • Recursively for deeper nested lists: If you have multiple levels of nesting, you can use a recursive approach.
def flatten(lst): result = [] for item in lst: if isinstance(item, list): result.extend(flatten(item)) else: result.append(item) return result nested_list = [1, [2, 3], [4, [5, 6]], 7] print(flatten(nested_list)) 

Each of these methods has its advantages. While list comprehension and loops work well for a single level of nesting, the recursive method is more general and can handle multiple levels of nested lists. However, recursion could lead to a stack overflow for very deeply nested lists.


More Tags

asp.net-core-webapi querystringparameter shared-hosting linked-tables properties-file chomp ienumerable min iis-7.5 jsf

More Programming Guides

Other Guides

More Programming Examples