Reputation: 115
I want to convert a normal list(main_list) into a nested one(ans_list) but I don't know how.
main_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
ans_list = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Upvotes: 0
Views: 52
Reputation: 535
if you are open to using NumPy and there are no other conditions other than how many rows you want to split in to then try this
import numpy as np
np.array(main_list).reshape(-1,3).tolist()
Upvotes: 1
Reputation: 73470
Use a comprehension over appropriate slices:
n = 3
ans_list = [main_list[i::n] for i in range(n)]
# [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Upvotes: 6