PYTHON
Flattening a Simple Nested List Non-Recursively
Learn to flatten a simple list of lists into a single flat list using Python's efficient list comprehensions or `itertools.chain`. This is useful for processing structured data.
import itertools
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
# Method 1: Using a nested list comprehension (for shallow nesting)
flat_list_comp = [item for sublist in nested_list for item in sublist]
print(f"Flattened with list comprehension: {flat_list_comp}")
# Method 2: Using itertools.chain.from_iterable (more efficient for large lists)
flat_list_chain = list(itertools.chain.from_iterable(nested_list))
print(f"Flattened with itertools.chain: {flat_list_chain}")
# Example with different types of data
data_from_api = [
["tag1", "tag2"],
["tag3"],
["tag1", "tag4", "tag5"]
]
all_tags = list(itertools.chain.from_iterable(data_from_api))
print(f"All tags from API data: {all_tags}")
How it works: Flattening a nested list means converting a list of lists into a single, flat list containing all elements. For a shallowly nested list (a list containing only other lists, not arbitrarily deep nesting), a nested list comprehension provides a concise and Pythonic way to achieve this. Alternatively, `itertools.chain.from_iterable` is often more memory-efficient for larger lists as it generates elements on demand rather than building an intermediate list. This snippet specifically avoids recursion to comply with the forbidden topics.