Ali
Ali

Reputation: 115

converting a normal list into a nested one using a condition

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

Answers (2)

Akshay Kadidal
Akshay Kadidal

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

user2390182
user2390182

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

Related Questions