This article will teach you how to use flatten lists using Python. You’ll discover numerous techniques for doing this, such as list comprehensions, for-loops, the itertools library, and recursion to flatten multi-level lists of lists. Let’s look at what you will discover in this tutorial!.
Flatten Lists of Lists
we can create flatten list using picking every element from the list of lists and putting it in a 1D list.
nested_list = [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]] flat_list = [] # Iterate through the outer list for element in nested_list: if type(element) is list: # If the element is of type list, iterate through the sublist for item in element: flat_list.append(item) else: flat_list.append(element) return flat_list print('List', nested_list) print('Flatten List', flat_list)
Output:
List [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]] Flatten List [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Flatten List of Lists Using a List Comprehension
This method offers an elegant but less natural way to build a flat list from a 2D list that already exists:
list = [[1, 2, 3, 4], [5, 6, 7], [8, 9]] flat_list = [item for sublist in list for item in sublist] print('Original list', list) print('Flatten list', flat_list)
Output:
List [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]] Flatten List [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Flatten List of Lists Using NumPy method
The Numpy also can be used to create flattened list.
import numpy regular_list = [[1, 2, 3, 4], [5, 6, 7], [8, 9]] flat_list = list(numpy.concatenate(regular_list).flat) print('list', regular_list) print('Flatten list', flat_list)
Output:
List [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]] Flatten List [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]