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)
- sunny asked 1 month ago
- You must login to post comments
Your Answer
Please login first to submit.