Python: How to Flatten a List of Lists

python_tutorials

Introduction

A list is the most flexible data structure in Python. Whereas, a 2D list which is commonly known as a list of lists, is a list object where every item is a list itself – for example: [[1,2,3], [4,5,6], [7,8,9]].

Flattening a list of lists entails converting a 2D list into a 1D list by un-nesting each list item stored in the list of lists – i.e., converting [[1, 2, 3], [4, 5, 6], [7, 8, 9]] into [1, 2, 3, 4, 5, 6, 7, 8, 9].

The process of flattening can be performed using nested for loops, list comprehensions, recursion, built-in functions or by importing libraries in Python depending on the regularity and depth of the nested lists.

Types of Nested Lists

Since Python is weakly typed, you can encounter regular and irregular lists of lists.

Regular List of Lists

Every element of this

 

 

To finish reading, please visit source site