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

Estimated read time 1 min read

To convert a 1D list to a 2D list in Python, you can use list comprehension or nested loops to split the elements of the 1D list into separate rows of the 2D list. Here’s an example using list comprehension:

list_1d = [1, 2, 3, 4, 5, 6]
num_columns = 3

list_2d = [list_1d[i:i+num_columns] for i in range(0, len(list_1d), num_columns)]

print(list_2d)

In the code above, we have a 1D list called list_1d with elements [1, 2, 3, 4, 5, 6]. We also specify the number of columns for the resulting 2D list using num_columns.

Using list comprehension, we iterate over the list_1d and create slices of length num_columns starting from index i and incrementing i by num_columns in each iteration. This allows us to split the 1D list into rows of the desired length.

The resulting 2D list list_2d will have rows with num_columns elements, and any remaining elements will form the last row.

The output will be:

[[1, 2, 3], [4, 5, 6]]

In this example, the 1D list [1, 2, 3, 4, 5, 6] is converted to a 2D list with two rows and three columns.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply