How to Convert a 2D List to a 1D List in Python?

Estimated read time 2 min read

To convert a 2D list to a 1D list in Python, you can use list comprehension along with the extend() method. Here’s an example:

# Define a 2D list
list_2d = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Convert 2D list to 1D list using list comprehension and extend method
list_1d = []
[list_1d.extend(row) for row in list_2d]

# Print the 1D list
print(list_1d)

In this example, we have a 2D list list_2d containing multiple rows, each representing a list of elements.

To convert the 2D list to a 1D list, we first initialize an empty list list_1d. Then, we use list comprehension to iterate over each row in the 2D list and extend list_1d by appending the elements of each row.

The extend() method is used to append multiple elements to an existing list. It takes an iterable as an argument and adds each element to the list.

The output will be:

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

In this case, the 2D list list_2d is converted to a 1D list list_1d that contains all the elements from the original 2D list in a flattened manner.

Note that the order of the elements in the resulting 1D list is determined by the order of the rows in the 2D list. Adjust the logic according to your specific requirements.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply