What is the method to convert a list of lists into a single flat list in Python?

0
0

To convert a list of lists into a single flat list in Python, you can use a nested for loop, a list comprehension, or the built-in itertools.chain() function. Here are examples of each approach:

Using nested for loops:

list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Using nested for loops to flatten the list
flat_list = []
for sublist in list_of_lists:
for item in sublist:
flat_list.append(item)

print(flat_list)

 

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Using a list comprehension:

list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Using a list comprehension to flatten the list
flat_list = [item for sublist in list_of_lists for item in sublist]

print(flat_list)

  • You must to post comments
Showing 0 results
Your Answer

Please first to submit.