import itertools # Define a list of lists list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # Flatten the list of lists using itertools.chain() flattened_list = list(itertools.chain(*list_of_lists)) # Print the flattened list print(flattened_list) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
To make a flat list out of a list of lists in Python, you can use the itertools.chain() function from the itertools module. This function takes a list of lists as an argument and returns an iterator that yields the elements of the inner lists one at a time.
In the example above, the my_lists variable contains a list of three lists, each containing three numbers. The itertools.chain() function is used to flatten this list of lists into a single list, which is then stored in the flattened_list variable. The flattened_list variable contains the elements from all of the sub-lists in the original list, in the order they appear.
Another way to flatten a list of lists in Python is to use a list comprehension. For example:
# Define a list of lists list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # Use a list comprehension to make a flat list flat_list = [x for sublist in list_of_lists for x in sublist] print(flat_list) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9 ]
In this example, the itertools.chain() function is used to flatten the nested_lists list of lists. The chain() function takes the nested_lists list as its argument, and returns an iterator that yields the elements from all of the lists in nested_lists. This iterator is then passed to the list() function, which creates a new list from the iterator's elements. The resulting list, which is stored in the flattened_list variable, contains all of the elements from the original lists, in the same order as they appeared in the original lists.
Learn Flask development and learn to build cool apps with our premium Python course on Udemy.