A list of lists in Python is a list where each element is itself a list. This can be useful for representing data in a tabular form, like a matrix or a 2D array.
# Creating a list of lists
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Accessing elements
print(matrix[0]) # Output: [1, 2, 3]
print(matrix[0][1]) # Output: 2
# Iterating through a list of lists
for row in matrix:
for element in row:
print(element, end=' ')
print()Flattening a list of lists means converting a list that contains sublists into a single list containing all the elements of the sublists. Here are some common methods:
def flatten_list(nested_list):
flat_list = []
for sublist in nested_list:
for element in sublist:
flat_list.append(element)
return flat_list
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(flatten_list(matrix))
# [1, 2, 3, 4, 5, 6, 7, 8, 9]def flatten_list(nested_list):
return [element for sublist in nested_list for element in sublist]itertools module, which is part of Python’s standard library. It provides the chain.from_iterable() function which efficiently flattens iterables. It takes an iterable of iterables (like your nested list) and returns a single iterator containing all elements. You can convert this to a list using list().from itertools import chain
def flatten_list(nested_list):
return list(chain.from_iterable(nested_list))functools.reduce() function from functools along with the operator.concat function to achieve flattening. It applies concat successively to elements in the list, flattening the structure.from functools import reduce
from operator import concat
def flatten_list(nested_list):
return reduce(concat, nested_list)