0

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]]
Ch3steR
  • 19,076
  • 4
  • 25
  • 52
Ali
  • 105
  • 5

2 Answers2

6

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]]
user2390182
  • 67,685
  • 6
  • 55
  • 77
1

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()
Akshay Kadidal
  • 511
  • 1
  • 7
  • 15