How to Reshape a Python List?

Estimated read time 2 min read

To reshape a Python list, you can use various approaches depending on your specific requirements. Here are a few methods to reshape a list:

  1. Using List Comprehension: List comprehension allows you to iterate over the original list and create a new list with the desired shape.
original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
num_rows = 2
num_columns = 5

reshaped_list = [[original_list[i * num_columns + j] for j in range(num_columns)]
                 for i in range(num_rows)]

print(reshaped_list)
  1. Using Numpy: If you have the Numpy library installed, you can use its reshape() function to reshape the list.
import numpy as np

original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
num_rows = 2
num_columns = 5

reshaped_array = np.array(original_list).reshape(num_rows, num_columns)
reshaped_list = reshaped_array.tolist()

print(reshaped_list)
  1. Using Iteration: If you prefer a more explicit approach, you can iterate over the original list and build the reshaped list step by step.
original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
num_rows = 2
num_columns = 5

reshaped_list = []
row = []
for i, item in enumerate(original_list):
    row.append(item)
    if (i + 1) % num_columns == 0:
        reshaped_list.append(row)
        row = []

print(reshaped_list)

These are three common methods for reshaping a Python list. Choose the one that best suits your needs and the tools available to you.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply